forked from yuduozhou/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPartitionList.java
60 lines (58 loc) · 1.62 KB
/
PartitionList.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode headSmall = new ListNode(0);
ListNode headLarge = new ListNode(0);
ListNode small = headSmall, large = headLarge;
while (head != null){
if (head.val < x){
small.next = head;
small = small.next;
}
else{
large.next = head;
large = large.next;
}
head = head.next;
small.next = null;
large.next = null;
}
small.next = headLarge.next;
return headSmall.next;
}
}
public class Solution {
public ListNode partition(ListNode head, int x) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode smaller = new ListNode(0);
ListNode larger = new ListNode(0);
ListNode h1 = smaller;
ListNode h2 = larger;
while(head != null){
if (head.val < x){
smaller.next = new ListNode(head.val);
smaller = smaller.next;
}
else{
larger.next = new ListNode(head.val);
larger= larger.next;
}
head = head.next;
}
smaller.next = h2.next;
return h1.next;
}
}