-
Notifications
You must be signed in to change notification settings - Fork 0
/
0086_Partition_List.java
36 lines (34 loc) · 1.09 KB
/
0086_Partition_List.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
// dummy nodes that point to the respective node lists
ListNode greaterHead = new ListNode(), lessHead = new ListNode();
// iterators for the respective lists
ListNode greater = greaterHead, less = lessHead;
// place each node into the list based on its value
while(head != null) {
if(head.val < x) {
less.next = head;
less = less.next;
head = head.next;
} else {
greater.next = head;
greater = greater.next;
head = head.next;
}
}
// truncate, connect, and return
greater.next = null;
less.next = greaterHead.next;
return lessHead.next;
}
}