86 Partition List

1. Question

Given a linked list and a valuex, partition it such that all nodes less thanxcome before nodes greater than or equal tox.
You should preserve the original relative order of the nodes in each of the two partitions.
For example, Given1->4->3->2->5->2andx= 3, return1->2->2->4->3->5.

2. Implementation

1
/**
2
* Definition for singly-linked list.
3
* public class ListNode {
4
* int val;
5
* ListNode next;
6
* ListNode(int x) { val = x; }
7
* }
8
*/
9
class Solution {
10
public ListNode partition(ListNode head, int x) {
11
if (head == null || head.next == null) {
12
return head;
13
}
14
15
ListNode less = new ListNode(0);
16
ListNode equalOrMore = new ListNode(0);
17
ListNode p1 = less;
18
ListNode p2 = equalOrMore;
19
20
ListNode curNode = head;
21
22
while (curNode != null) {
23
if (curNode.val < x) {
24
p1.next = curNode;
25
p1 = p1.next;
26
}
27
else {
28
p2.next = curNode;
29
p2 = p2.next;
30
}
31
curNode = curNode.next;
32
}
33
34
p2.next = null;
35
p1.next = equalOrMore.next;
36
return less.next;
37
}
38
}
Copied!

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)