Question
Formatted question description: https://leetcode.ca/all/86.html
86 Partition List
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.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
@tag-linkedlist
Algorithm
All nodes less than the given value are taken out to form a new linked list. At this time, the values of the remaining nodes in the original linked list are greater than or equal to the given value, as long as the original linked list is directly connected to the new linked list.
Original: 1 -> 4 -> 3 -> 2 -> 5 -> 2
New:
Original: 4 -> 3 -> 2 -> 5 -> 2
New: 1
Original: 4 -> 3 -> 5 -> 2
New: 1 -> 2
Original: 4 -> 3 -> 5
New: 1 -> 2 -> 2
Original:
New: 1 -> 2 -> 2 -> 4 -> 3 -> 5
Code
Java
public class Partition_List {
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null) {
return head;
}
ListNode lessList = new ListNode(0);
ListNode moreList = new ListNode(0);
ListNode lessHeadCopy = lessList;
ListNode moreHeadCopy = moreList;
int xCount = 0;
ListNode current = head;
while (current != null) {
int num = current.val;
if (num < x) {
lessList.next = new ListNode(num);
lessList = lessList.next;
} else {
moreList.next = new ListNode(num);
moreList = moreList.next;
}
current = current.next;
}
// append target x
while (xCount > 0) {
lessList.next = new ListNode(x);
lessList = lessList.next;
xCount--;
}
// connect two lists
lessList.next = moreHeadCopy.next;
return lessHeadCopy.next;
}
}
}