題目
Sort a linked list using insertion sort.
思路
這道題花費了最多的時間。
- 復習了array的插入排序,用兩個循環實現,每次循環到下一個數,和之前的比較,往前不斷挪動位置
- 運用在array的東西挪到linkedlist上就變得比較麻煩。 但基本思路和array操作一樣
- 有一個優化,直接把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