Skip to content

Commit 15b648d

Browse files
committed
rewrite
1 parent 21da0cd commit 15b648d

File tree

1 file changed

+24
-34
lines changed

1 file changed

+24
-34
lines changed

PartitionList.java

Lines changed: 24 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
2-
31
/**
42
* Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
53
*
@@ -12,36 +10,28 @@
1210

1311
public class PartitionList {
1412
public ListNode partition(ListNode head, int x) {
15-
ListNode low = null;
16-
ListNode high = null;
17-
ListNode cl = null;
18-
ListNode ch = null;
19-
ListNode cur = head;
20-
while (cur != null) {
21-
if (cur.val < x) {
22-
ListNode newNode = new ListNode(cur.val);
23-
if (low != null) {
24-
cl.next = newNode;
25-
} else {
26-
low = newNode;
27-
}
28-
cl = newNode;
29-
} else {
30-
ListNode newNode = new ListNode(cur.val);
31-
if (high != null) {
32-
ch.next = newNode;
33-
} else {
34-
high = newNode;
35-
}
36-
ch = newNode;
37-
}
38-
cur = cur.next;
39-
}
40-
if (low != null) {
41-
cl.next = high;
42-
return low;
43-
} else {
44-
return high;
45-
}
46-
}
13+
ListNode start = new ListNode(0);
14+
start.next = head;
15+
ListNode slow = start;
16+
while (slow.next != null) {
17+
if (slow.next.val < x) {
18+
slow = slow.next;
19+
} else {
20+
break;
21+
}
22+
}
23+
ListNode fast = slow;
24+
while (fast.next != null) {
25+
if (fast.next.val >= x) {
26+
fast = fast.next;
27+
} else {
28+
ListNode target = fast.next;
29+
fast.next = target.next;
30+
target.next = slow.next;
31+
slow.next = target;
32+
slow = slow.next;
33+
}
34+
}
35+
return start.next;
36+
}
4737
}

0 commit comments

Comments
 (0)