Skip to content

Commit 599429f

Browse files
add a solution for 143
1 parent 17be791 commit 599429f

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

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

+39
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,43 @@ public void reorderList(ListNode head) {
5151
}
5252
}
5353
}
54+
55+
public static class Solution2 {
56+
/**
57+
* My completely original solution on 10/25/2021, although not super efficient in time complexity,
58+
* since I keep going through the rest of the list to the end at each iteration, it's accepted on LeetCode.
59+
*/
60+
public void reorderList(ListNode head) {
61+
int len = getLen(head);
62+
if (len <= 2) {
63+
return;
64+
}
65+
ListNode curr = head;
66+
for (int i = 0; i < len / 2; i++) {
67+
ListNode tmp = curr;
68+
ListNode newHead = curr.next;
69+
while (tmp.next.next != null) {
70+
tmp = tmp.next;
71+
}
72+
if (tmp == curr) {
73+
break;
74+
}
75+
ListNode tail = tmp.next;
76+
tmp.next = null;
77+
curr.next = tail;
78+
tail.next = newHead;
79+
curr = newHead;
80+
}
81+
}
82+
83+
private int getLen(ListNode head) {
84+
int len = 0;
85+
ListNode tmp = head;
86+
while (tmp != null) {
87+
tmp = tmp.next;
88+
len++;
89+
}
90+
return len;
91+
}
92+
}
5493
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.common.classes.ListNode;
4+
import com.fishercoder.common.utils.LinkedListUtils;
5+
import com.fishercoder.solutions._143;
6+
import com.fishercoder.solutions._1862;
7+
import org.junit.BeforeClass;
8+
import org.junit.Test;
9+
10+
import java.util.Arrays;
11+
12+
import static org.junit.Assert.assertEquals;
13+
14+
public class _143Test {
15+
private static _143.Solution1 solution1;
16+
private static _143.Solution2 solution2;
17+
private static ListNode head;
18+
private static ListNode expected;
19+
20+
@BeforeClass
21+
public static void setup() {
22+
solution1 = new _143.Solution1();
23+
solution2 = new _143.Solution2();
24+
}
25+
26+
@Test
27+
public void test1() {
28+
head = LinkedListUtils.createSinglyLinkedList(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
29+
expected = LinkedListUtils.createSinglyLinkedList(Arrays.asList(1, 7, 2, 6, 3, 5, 4));
30+
solution1.reorderList(head);
31+
assertEquals(expected, head);
32+
}
33+
34+
@Test
35+
public void test2() {
36+
head = LinkedListUtils.createSinglyLinkedList(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
37+
expected = LinkedListUtils.createSinglyLinkedList(Arrays.asList(1, 7, 2, 6, 3, 5, 4));
38+
solution2.reorderList(head);
39+
assertEquals(expected, head);
40+
}
41+
}

0 commit comments

Comments
 (0)