-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCProblem86.cs
More file actions
92 lines (83 loc) · 2.98 KB
/
LCProblem86.cs
File metadata and controls
92 lines (83 loc) · 2.98 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
89
90
91
/*
86. Partition List
Medium
Given the head of 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.
You should preserve the original relative order of the nodes in each of the two partitions.
Passes - Beats 34% of C# users
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode Partition(ListNode head, int x) {
if(head == null) return head;
if(head.next == null) return head;
// if we are partitioning on the start of the list
// find the first value less than x, and create a new list with that
ListNode newHead = new ListNode(-201, null);;
if(head.val >= x) {
// find the first value less than x
ListNode tmpNode = head.next;
while(tmpNode != null) {
if(tmpNode.val < x) {
newHead.val = tmpNode.val;
break;
}
tmpNode = tmpNode.next;
}
// if no such value is found, the list is sorted
if(tmpNode == null) return head;
// find the rest of the values less than x and attach to the newList
ListNode newList = newHead;
tmpNode = tmpNode.next;
while(tmpNode != null) {
if(tmpNode.val < x) {
newList.next = new ListNode(tmpNode.val, null);
newList = newList.next;
}
tmpNode = tmpNode.next;
}
// now find all values >= x and add them to the list
tmpNode = head;
while(tmpNode != null) {
if(tmpNode.val >= x) {
newList.next = new ListNode(tmpNode.val, null);
newList = newList.next;
}
tmpNode = tmpNode.next;
}
}
// else we need to find the node right before the first value >= x
else {
// put all of the values < x on the list in order
ListNode tmpNode = head.next;
newHead.val = head.val;
ListNode newList = newHead;
while(tmpNode != null) {
if(tmpNode.val < x) {
newList.next = new ListNode(tmpNode.val, null);
newList = newList.next;
}
tmpNode = tmpNode.next;
}
// put all of the values >= x on the list in order
tmpNode = head;
while(tmpNode != null) {
if(tmpNode.val >= x) {
newList.next = new ListNode(tmpNode.val, null);
newList = newList.next;
}
tmpNode = tmpNode.next;
}
}
return newHead;
}
}