-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0086PartitionList.java
More file actions
88 lines (72 loc) · 2.2 KB
/
_0086PartitionList.java
File metadata and controls
88 lines (72 loc) · 2.2 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.heatwave.leetcode.problems;
public class _0086PartitionList {
private static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
static class Solution {
public ListNode partition(ListNode head, int x) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode current = dummy;
while (current.next != null && current.next.val < x) {
current = current.next;
}
ListNode left = current, right = current.next;
while (right != null) {
if (right.val < x) {
left.next = right.next;
right.next = current.next;
current.next = right;
current = right;
right = left.next;
continue;
}
left = left.next;
right = right.next;
}
return dummy.next;
}
}
static class AnotherSolution {
public ListNode partition(ListNode head, int x) {
ListNode less = null, lessHead = head, gte = null, gteHead = null;
while (head != null) {
if (head.val < x) {
if (less == null) {
less = head;
lessHead = head;
} else {
less.next = head;
less = head;
}
} else {
if (gte == null) {
gte = head;
gteHead = head;
} else {
gte.next = head;
gte = head;
}
}
head = head.next;
}
if (less != null) {
less.next = gteHead;
}
if (gte != null) {
gte.next = null;
}
return lessHead;
}
}
}