原題地址:http://oj.leetcode.com/problems/sort-list/數組
題意:鏈表的排序。要求:時間複雜度O(nlogn),空間複雜度O(1)。spa
解題思路:因爲題目對時間複雜度和空間複雜度要求比較高,因此查看了各類解法,最好的解法就是歸併排序,因爲鏈表在歸併操做時並不須要像數組的歸併操做那樣分配一個臨時數組空間,因此這樣就是常數空間複雜度了,固然這裏不考慮遞歸所產生的系統調用的棧。指針
這裏涉及到一個鏈表經常使用的操做,即快慢指針的技巧。設置slow和fast指針,開始它們都指向表頭,fast每次走兩步,slow每次走一步,fast到鏈表尾部時,slow正好到中間,這樣就將鏈表截爲兩段。code
運行時須要將中文註釋刪掉,leetcode oj平臺裏面不支持中文字符。blog
代碼:排序
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a ListNode def merge(self, head1, head2): if head1 == None: return head2 if head2 == None: return head1 dummy = ListNode(0) #歸併時,新建一個鏈表頭結點 p = dummy while head1 and head2: if head1.val <= head2.val: p.next = head1 head1 = head1.next p = p.next else: p.next = head2 head2 = head2.next p = p.next if head1 == None: p.next = head2 if head2 == None: p.next = head1 return dummy.next def sortList(self, head): if head == None or head.next == None: return head slow = head; fast = head #快慢指針技巧的運用,用來截斷鏈表。 while fast.next and fast.next.next: slow = slow.next fast = fast.next.next head1 = head head2 = slow.next slow.next = None #head1和head2爲截爲兩條鏈表的表頭 head1 = self.sortList(head1) head2 = self.sortList(head2) head = self.merge(head1, head2) return head