-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution24.java
More file actions
executable file
·39 lines (38 loc) · 1.12 KB
/
Copy pathSolution24.java
File metadata and controls
executable file
·39 lines (38 loc) · 1.12 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution24 {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode res = new ListNode(-1, head.next);
while (head != null) {
if (head.next == null) break;
ListNode slow = head;
ListNode fast = head.next;
slow.next = fast.next;
fast.next = slow;
head = head.next;
if (slow.next != null && slow.next.next != null)
slow.next = slow.next.next;
}
return res.next;
}
public ListNode reswapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode one = head;
ListNode two = one.next;
ListNode three = two.next;
two.next = one;
one.next = reswapPairs(three);
return two;
}
}