class Solution: def sortList(self, head): # QuickSort len = 0 tail = head while tail != None: len += 1 tail = tail.next pivot = head return self.partition(head, len) def partition(self, head, len): if len<2: return head pivot = head r_pivot = pivot tail = head head = ListNode(0) left = head l = 0 lr = 0 stall = 0 l_len = 0 r_len = len-1 while tail.next != None and l<len-1: if tail.next.val < pivot.val: left.next = tail.next left = left.next tail.next = tail.next.next r_len -= 1 l_len += 1 lr += 1 left.next = pivot elif tail.next.val > pivot.val: tail = tail.next elif tail.next.val == pivot.val: self.swap_nodes(r_pivot, r_pivot.next, tail, tail.next) lr += 1 stall = l-lr if r_pivot == tail: tail = r_pivot.next r_pivot = r_pivot.next r_len -= 1 if stall>0: stall -= 1 else: l += 1 left.next = pivot head_l = self.partition(head.next, l_len) head_r = self.partition(r_pivot.next, r_len) head.next = head_l r_pivot.next = head_r return head.next def swap_nodes(self, x, a, y, b): x.next = b y.next = a temp = a.next a.next = b.next b.next = temp
Thursday, September 18, 2014
Leetcode: Sort List @Python
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment