-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSwapNodesInPairs.java
More file actions
52 lines (43 loc) · 1.13 KB
/
Copy pathSwapNodesInPairs.java
File metadata and controls
52 lines (43 loc) · 1.13 KB
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
package linkedlist;
// Source : https://leetcode.com/problems/swap-nodes-in-pairs/
// Id : 24
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2021/10/29
// Topic : linkedlist
// Level : Medium-
// Other :
// Tips :
// Links :
// Result : 100% 55.56%
public class SwapNodesInPairs {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode sentinel = new ListNode(-1, head);
ListNode pre = sentinel, cur = head, tmp = head;
while (cur != null) {
if (cur.next == null)
return sentinel.next;
pre.next = cur.next;
tmp = cur.next;
cur.next = cur.next.next;
tmp.next = cur;
pre = cur;
cur = cur.next;
}
return sentinel.next;
}
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}