forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_24.java
50 lines (46 loc) · 1.36 KB
/
_24.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
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
public class _24 {
public static class Solution1 {
/**
* Recursive solution.
*/
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode second = head.next;
ListNode third = second.next;
second.next = head;
head.next = swapPairs(third);
return second;
}
}
public static class Solution2 {
/**
* Iterative approach:
* My completely original on 10/24/2021.
*/
public ListNode swapPairs(ListNode head) {
ListNode pre = new ListNode(-1);
pre.next = head;
ListNode tmp = pre;
while (head != null) {
ListNode third;
ListNode first = head;
ListNode second = head.next;
if (second == null) {
break;
} else {
third = head.next.next;
second.next = first;
first.next = third;
tmp.next = second;
tmp = tmp.next.next;
}
head = third;
}
return pre.next;
}
}
}