147. Insertion Sort List

題目

Sort a linked list using insertion sort.

思路

這道題花費了最多的時間。

  1. 復習了array的插入排序,用兩個循環實現,每次循環到下一個數,和之前的比較,往前不斷挪動位置
  2. 運用在array的東西挪到linkedlist上就變得比較麻煩。 但基本思路和array操作一樣
  3. 有一個優化,直接把tle變成通過,就是每次只當cur的值小于當前head值時,才把cur回移動到最開始

Python

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

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

class Solution(object):
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        #something really easy on array become really hard on Linked list!!!
        cur = dummy = ListNode(0) #The returning list, use it to iterate from start each time
        while head:
            if cur and cur.val > head.val: # Added a line to do the optmization
                cur = dummy # The "pre" pointer will help us find out the right position
            while cur.next and cur.next.val < head.val: #move the pre pointer to find the right place
                cur = cur.next
            
            cur.next, cur.next.next, head = head, cur.next, head.next
        return dummy.next
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容