Skip to content

Commit 44bf19c

Browse files
committed
add solution of problem 86: partition list
1 parent d137570 commit 44bf19c

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

PartitionList86/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
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*.
2+
3+
You should preserve the original relative order of the nodes in each of the two partitions.
4+
5+
For example,
6+
Given `1->4->3->2->5->2` and *x* = 3,
7+
return `1->2->2->4->3->5`.

PartitionList86/Solution.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
public class Solution {
10+
public ListNode partition(ListNode head, int x) {
11+
if (head == null) {
12+
return null;
13+
}
14+
15+
ListNode ltHead = null;
16+
ListNode ltNode = null;
17+
ListNode geHead = null;
18+
ListNode geNode = null;
19+
ListNode currNode = head;
20+
21+
while (currNode != null) {
22+
if (currNode.val < x) {
23+
if (ltHead == null) {
24+
ltHead = currNode;
25+
ltNode = currNode;
26+
} else {
27+
ltNode.next = currNode;
28+
ltNode = ltNode.next;
29+
}
30+
} else {
31+
if (geHead == null) {
32+
geHead = currNode;
33+
geNode = currNode;
34+
} else {
35+
geNode.next = currNode;
36+
geNode = geNode.next;
37+
}
38+
}
39+
40+
currNode = currNode.next;
41+
}
42+
43+
if (geNode != null) {
44+
geNode.next = null;
45+
}
46+
47+
if (ltNode != null) {
48+
ltNode.next = geHead;
49+
} else {
50+
ltHead = geHead;
51+
}
52+
53+
return ltHead;
54+
}
55+
}

0 commit comments

Comments
 (0)