Skip to content

Commit 8b9c165

Browse files
add a solution for 24
1 parent 9fbb852 commit 8b9c165

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

src/main/java/com/fishercoder/solutions/_24.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
public class _24 {
66
public static class Solution1 {
7+
/**
8+
* Recursive solution.
9+
*/
710
public ListNode swapPairs(ListNode head) {
811
if (head == null || head.next == null) {
912
return head;
@@ -16,4 +19,32 @@ public ListNode swapPairs(ListNode head) {
1619
}
1720
}
1821

22+
public static class Solution2 {
23+
/**
24+
* Iterative approach:
25+
* My completely original on 10/24/2021.
26+
*/
27+
public ListNode swapPairs(ListNode head) {
28+
ListNode pre = new ListNode(-1);
29+
pre.next = head;
30+
ListNode tmp = pre;
31+
while (head != null) {
32+
ListNode third;
33+
ListNode first = head;
34+
ListNode second = head.next;
35+
if (second == null) {
36+
break;
37+
} else {
38+
third = head.next.next;
39+
second.next = first;
40+
first.next = third;
41+
tmp.next = second;
42+
tmp = tmp.next.next;
43+
}
44+
head = third;
45+
}
46+
return pre.next;
47+
}
48+
}
49+
1950
}
Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,39 @@
11
package com.fishercoder;
22

33
import com.fishercoder.common.classes.ListNode;
4-
import com.fishercoder.common.utils.CommonUtils;
54
import com.fishercoder.common.utils.LinkedListUtils;
65
import com.fishercoder.solutions._24;
76
import org.junit.BeforeClass;
87
import org.junit.Test;
98

109
import java.util.Arrays;
1110

11+
import static org.junit.Assert.assertEquals;
12+
1213
public class _24Test {
1314
private static _24.Solution1 solution1;
15+
private static _24.Solution2 solution2;
1416
private static ListNode head;
17+
private static ListNode expected;
1518

1619
@BeforeClass
1720
public static void setup() {
1821
solution1 = new _24.Solution1();
22+
solution2 = new _24.Solution2();
1923
}
2024

2125
@Test
2226
public void test1() {
2327
head = LinkedListUtils.createSinglyLinkedList(Arrays.asList(1, 2, 3, 4));
24-
CommonUtils.printList(solution1.swapPairs(head));
28+
expected = LinkedListUtils.createSinglyLinkedList(Arrays.asList(2, 1, 4, 3));
29+
assertEquals(expected, solution1.swapPairs(head));
30+
}
31+
32+
@Test
33+
public void test2() {
34+
head = LinkedListUtils.createSinglyLinkedList(Arrays.asList(1, 2, 3, 4));
35+
expected = LinkedListUtils.createSinglyLinkedList(Arrays.asList(2, 1, 4, 3));
36+
assertEquals(expected, solution2.swapPairs(head));
2537
}
2638

2739
}

0 commit comments

Comments
 (0)