File tree Expand file tree Collapse file tree 1 file changed +24
-34
lines changed Expand file tree Collapse file tree 1 file changed +24
-34
lines changed Original file line number Diff line number Diff line change 1
-
2
-
3
1
/**
4
2
* 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.
5
3
*
12
10
13
11
public class PartitionList {
14
12
public ListNode partition (ListNode head , int x ) {
15
- ListNode low = null ;
16
- ListNode high = null ;
17
- ListNode cl = null ;
18
- ListNode ch = null ;
19
- ListNode cur = head ;
20
- while (cur != null ) {
21
- if (cur .val < x ) {
22
- ListNode newNode = new ListNode (cur .val );
23
- if (low != null ) {
24
- cl .next = newNode ;
25
- } else {
26
- low = newNode ;
27
- }
28
- cl = newNode ;
29
- } else {
30
- ListNode newNode = new ListNode (cur .val );
31
- if (high != null ) {
32
- ch .next = newNode ;
33
- } else {
34
- high = newNode ;
35
- }
36
- ch = newNode ;
37
- }
38
- cur = cur .next ;
39
- }
40
- if (low != null ) {
41
- cl .next = high ;
42
- return low ;
43
- } else {
44
- return high ;
45
- }
46
- }
13
+ ListNode start = new ListNode (0 );
14
+ start .next = head ;
15
+ ListNode slow = start ;
16
+ while (slow .next != null ) {
17
+ if (slow .next .val < x ) {
18
+ slow = slow .next ;
19
+ } else {
20
+ break ;
21
+ }
22
+ }
23
+ ListNode fast = slow ;
24
+ while (fast .next != null ) {
25
+ if (fast .next .val >= x ) {
26
+ fast = fast .next ;
27
+ } else {
28
+ ListNode target = fast .next ;
29
+ fast .next = target .next ;
30
+ target .next = slow .next ;
31
+ slow .next = target ;
32
+ slow = slow .next ;
33
+ }
34
+ }
35
+ return start .next ;
36
+ }
47
37
}
You can’t perform that action at this time.
0 commit comments