-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-24-Swap-Nodes-in-Pairs.java
72 lines (56 loc) · 1.94 KB
/
LeetCode-24-Swap-Nodes-in-Pairs.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
LeetCode: https://leetcode.com/problems/swap-nodes-in-pairs/
LintCode: http://www.lintcode.com/problem/swap-nodes-in-pairs/
JiuZhang: http://www.jiuzhang.com/solutions/swap-nodes-in-pairs/
ProgramCreek: http://www.programcreek.com/2014/04/leetcode-swap-nodes-in-pairs-java/
Analysis:
Two pointers
Runtime: 0 ms, faster than 100.00% of Java online submissions for Swap Nodes in Pairs.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
// 1.
// public ListNode swapPairs(ListNode head) {
// if (head == null || head.next == null) return head;
// ListNode dummy = new ListNode(-1);
// dummy.next = head;
// ListNode slow = dummy, fast = head;
// while(fast != null && fast.next != null) {
// ListNode temp = fast.next;
// fast.next = fast.next.next;
// slow.next = temp;
// temp.next = fast;
// slow = slow.next.next;
// fast = fast.next;
// }
// return dummy.next;
// }
// 2.
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
while(pre.next != null && pre.next.next != null){
ListNode p1 = pre.next;
ListNode p2 = pre.next.next;
// Three stops:
// 1.change p1's next node
p1.next = p2.next;
// 2.change p2's next node
p2.next = p1;
// 3.change pre node's next node
pre.next = p2;
// 4.change the pre node to next round's pre node
pre = p1;
}
return dummy.next;
}
}