Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite085086

Browse files
author
applewjg
committed
SwapNodesinPairs
Change-Id: I47ad89d68b6e53f04ae2e564f732964895ff002c
1 parent76a4eb3 commite085086

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

‎SwapNodesinPairs.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 20, 2014
4+
Problem: Swap Nodes in Pairs
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/swap-nodes-in-pairs/
7+
Notes:
8+
Given a linked list, swap every two adjacent nodes and return its head.
9+
For example,
10+
Given 1->2->3->4, you should return the list as 2->1->4->3.
11+
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
12+
13+
Solution: 1. Iterative solution with constant space.
14+
2. Recursive solution with O(n) space (for practice).
15+
*/
16+
17+
/**
18+
* Definition for singly-linked list.
19+
* public class ListNode {
20+
* int val;
21+
* ListNode next;
22+
* ListNode(int x) {
23+
* val = x;
24+
* next = null;
25+
* }
26+
* }
27+
*/
28+
publicclassSolution {
29+
publicListNodeswapPairs_1(ListNodehead) {
30+
if (head ==null ||head.next ==null)returnhead;
31+
ListNodedummy =newListNode(0);
32+
dummy.next =head;
33+
ListNodecur =dummy;
34+
while (cur.next !=null &&cur.next.next !=null) {
35+
ListNodenode =cur.next.next;
36+
cur.next.next =node.next;
37+
node.next =cur.next;
38+
cur.next =node;
39+
cur =node.next;
40+
}
41+
returndummy.next;
42+
}
43+
publicListNodeswapPairs(ListNodehead) {
44+
if (head ==null ||head.next ==null)returnhead;
45+
ListNodefirst =head,second =head.next;
46+
first.next =second.next;
47+
second.next =first;
48+
first.next =swapPairs(first.next);
49+
returnsecond;
50+
}
51+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp