-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0024. Swap Nodes in Pairs
54 lines (50 loc) · 1.47 KB
/
0024. Swap Nodes in Pairs
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
class Solution {
// public ListNode swapPairs(ListNode head) {
// if (head == null) {
// return head;
// }
// ListNode p = head;
// HashMap<Integer, ListNode> map = new HashMap<>();
// int n = 0;
// while (p != null) {
// map.put(n++, p);
// p = p.next;
// }
// ListNode last = null;
// if (n % 2 == 1) {
// last = map.get(n - 1);
// map.remove(n - 1);
// }
// ListNode root = new ListNode(0);
// p = root;
// for (int i = 0; i < map.size() / 2; i++) {
// p.next = map.get(2 * i + 1);
// p = p.next;
// p.next = map.get(2 * i);
// p = p.next;
// }
// if (last != null) {
// p.next = last;
// p = p.next;
// }
// p.next = null;
// return root.next;
// }
public ListNode swapPairs(ListNode head) {
if (head == null) {
return head;
}
ListNode root = new ListNode(-1);
root.next = head;
ListNode pre = root, curr = head;
while (curr != null && curr.next != null) {
pre.next = curr.next;
pre = pre.next;
curr.next = curr.next.next;
pre.next = curr;
pre = pre.next;
curr = pre.next;
}
return root.next;
}
}