Leetcode[86] Partition List
06 Nov 2015###Task 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.
###Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
leftS = ListNode(0)
leftHead = leftS
rightS = ListNode(0)
rightHead = rightS
if head == None or head.next == None:
return head
while head:
if head.val < x:
leftHead.next = ListNode(head.val)
leftHead = leftHead.next
else:
rightHead.next = ListNode(head.val)
rightHead = rightHead.next
head = head.next
leftHead.next = rightS.next
return leftS.next
###Java
/**
* 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 null;
}
ListNode leftDummy = new ListNode(0);
ListNode rightDummy = new ListNode(0);
ListNode leftPoint = leftDummy;
ListNode rightPoint = rightDummy;
while (head != null) {
if (head.val < x) {
leftPoint.next = head;
leftPoint = leftPoint.next;
} else {
rightPoint.next = head;
rightPoint = rightPoint.next;
}
head = head.next;
}
//remember to make rightPoint points to null
rightPoint.next = null;
leftPoint.next = rightDummy.next;
return leftDummy.next;
}
}
###Points
- Head change –> dummy
- First step of quick sort
- O(n)
- Remember to change rightPoint.next to null!! tail always needs to be Null