Minimum Path Sum @ LeetCode (Python)
Partition List @ LeetCode (Python)

Sort List @ LeetCode (Python)

kitt posted @ 2014年3月15日 13:16 in LeetCode , 2636 阅读

Merge sort

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @return a ListNode
    def sortList(self, head):
        length = 0
        curr = head;
        while curr != None:
            length += 1
            curr = curr.next
        return self.mergeSort(head, length)
    
    def mergeSort(self, head, length):
        # base case
        if length == 1 or length == 0: return head
        
        # sort the two halves of the list
        prev = curr = head
        for i in xrange(length / 2): curr = curr.next
        for i in xrange(length / 2 - 1): prev = prev.next
        prev.next = None
        head1 = self.mergeSort(head, length / 2)
        head2 = self.mergeSort(curr, length - length / 2)
        
        # merge sorted halves into one
        if head1.val <= head2.val: 
            curr = newHead = ListNode(head1.val)
            head1 = head1.next
        else: 
            curr = newHead = ListNode(head2.val)
            head2 = head2.next
        while head1 and head2:
            if head1.val <= head2.val:
                curr.next = ListNode(head1.val)
                head1 = head1.next
            else:
                curr.next = ListNode(head2.val)
                head2 = head2.next
            curr = curr.next
        while head1:
            curr.next = ListNode(head1.val)
            head1 = head1.next
            curr = curr.next
        while head2:
            curr.next = ListNode(head2.val)
            head2 = head2.next
            curr = curr.next
        return newHead
Avatar_small
xyz 说:
2014年4月29日 13:33

你这个是跟array的merge sort一个写法?要先过一遍 看这个: http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html

不过需要另开一个linked list

Avatar_small
Paul 说:
2014年6月20日 12:10

Would it be better to replace

for i in xrange(length / 2): curr = curr.next
for i in xrange(length / 2 - 1): prev = prev.next

with

for i in xrange(length / 2):
curr = curr.next
if i!=0:
prev = prev.next

?


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter