Skip to content

Commit 81dacbe

Browse files
add a solution for 86
1 parent 9461a37 commit 81dacbe

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

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

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

33
import com.fishercoder.common.classes.ListNode;
44

5+
import java.util.ArrayList;
6+
import java.util.List;
7+
58
public class _86 {
69
public static class Solution1 {
710
public ListNode partition(ListNode head, int x) {
@@ -27,4 +30,32 @@ public ListNode partition(ListNode head, int x) {
2730
return left.next;
2831
}
2932
}
33+
34+
public static class Solution2 {
35+
public ListNode partition(ListNode head, int x) {
36+
List<Integer> first = new ArrayList<>();
37+
List<Integer> last = new ArrayList<>();
38+
while (head != null) {
39+
if (head.val < x) {
40+
first.add(head.val);
41+
} else {
42+
last.add(head.val);
43+
}
44+
head = head.next;
45+
}
46+
ListNode pre = new ListNode(-1);
47+
ListNode tmp = pre;
48+
int i = 1;
49+
int j = 0;
50+
while (i < first.size() || j < last.size()) {
51+
if (i < first.size()) {
52+
tmp.next = new ListNode(first.get(i++));
53+
} else if (j < last.size()) {
54+
tmp.next = new ListNode(last.get(j++));
55+
}
56+
tmp = tmp.next;
57+
}
58+
return pre.next;
59+
}
60+
}
3061
}

src/test/java/com/fishercoder/_86Test.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,22 @@
1212

1313
public class _86Test {
1414
private static _86.Solution1 solution1;
15+
private static _86.Solution2 solution2;
1516
private static ListNode head;
1617
private static ListNode expected;
1718

1819
@BeforeClass
1920
public static void setup() {
2021
solution1 = new _86.Solution1();
22+
solution2 = new _86.Solution2();
2123
}
2224

2325
@Test
2426
public void test1() {
2527
head = LinkedListUtils.createSinglyLinkedList(Arrays.asList(1, 4, 3, 2, 5, 2));
2628
expected = LinkedListUtils.createSinglyLinkedList(Arrays.asList(1, 2, 2, 4, 3, 5));
2729
assertEquals(expected, (solution1.partition(head, 3)));
30+
assertEquals(expected, (solution2.partition(head, 3)));
2831
}
2932

3033
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy