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.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
Seen this question in a real interview before? YesNo
Difficulty:Medium
Total Accepted:137.2K
Total Submissions:393.7K
Contributor:LeetCode
Subscribe to see which companies asked this question.
Related Topics
Linked ListTwo Pointers
Java
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){
12
return null;
13
}
14
ListNode largeHeadNode = null;
15
ListNode largeTailNode = null;
16
ListNode lessHeadNode = null;
17
ListNode lessTailNode = null;
18
ListNode temp = head;
19
while(temp!=null){
20
if(temp.val >=x ){
21
if(largeTailNode ==null){
22
largeHeadNode = temp;
23
largeTailNode = temp;
24
}else{
25
largeTailNode.next = temp;
26
largeTailNode = temp;
27
}
28
}else{
29
if(lessTailNode == null){
30
lessTailNode = temp;
31
lessHeadNode = temp;
32
}else{
33
lessTailNode.next = temp;
34
lessTailNode = temp;
35
}
36
}
37
temp = temp.next;
38
39
}
40
if(largeTailNode !=null){
41
largeTailNode.next = null;
42
}
43
if(lessTailNode !=null){
44
lessTailNode.next = largeHeadNode;
45
}
46
if(lessHeadNode == null){
47
return largeHeadNode;
48
}
49
return lessHeadNode;
50
51
52
}
53
54
55
}