Leetcode刷題_148:SortList

Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        #鏈表歸併排序
        if not head  or not head.next:
        	return head
        #利用快慢指針尋找中間節點
        fast = head.next #因爲leetcode是默認沒有頭節點
        slow = head
        while fast and fast.next:
        	fast = fast.next.next
        	slow = slow.next
        fast = slow.next
        slow.next = None
        slow = self.sortList(head)
        fast = self.sortList(fast)
        return self.merge(slow,fast)
     
    def merge(self, head1, head2):
    	if head1 == None:
    		return head2
    	if head2 == None:
    		return head1
    	cur1 = head1
    	cur2 = head2
    	head = None
    	if head1.val<head2.val:
    		head = head1
    		cur1 = cur1.next
    	else:
    		head = head2
    		cur2 = cur2.next
    	cur = head
    	while cur1 and cur2:
    		if cur1.val<cur2.val:
    			cur.next = cur1
    			cur = cur1
    			cur1 = cur1.next
    		else:
    			cur.next = cur2
    			cur = cur2
    			cur2 = cur2.next
        # cur1 and cur2 at least one is None
        cur.next = cur1 or cur2
        return head
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章