-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPartition List
More file actions
40 lines (40 loc) · 1.14 KB
/
Partition List
File metadata and controls
40 lines (40 loc) · 1.14 KB
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
37
38
39
40
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == null)
return null;
ListNode front = new ListNode(0);
ListNode pivot = new ListNode(x);
ListNode less = front, larger = pivot;
ListNode current = head;
while(current != null)
{
ListNode next = current.next;
if(current.val < x)
{
less.next = current;
less = current;
}
else{
larger.next = current;
larger = current;
larger.next = null; //set the last node and fresh each time
}
current = next;
}//end while
less.next = pivot.next; //connect these two lists
return front.next;
}
}