题目:
Sort a linked list using insertion sort.
代码:oj测试通过 Runtime: 860 ms
# 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 insertionSortList(self, head): if head is None or head.next is None:
return head dummyhead = ListNode(0)
dummyhead.next = head curr = dummyhead.next
while curr.next is not None:
if curr.next.val < curr.val:
pre = dummyhead
while pre.next.val < curr.next.val:
pre = pre.next
tmp = curr.next
curr.next = tmp.next
tmp.next = pre.next
pre.next = tmp
else:
curr = curr.next return dummyhead.next
思路:
首先要知道插入排序的原理。
对于单链表来说,需要做指针的交换。
小白记忆插入排序的原理只有一句话:类比扑克牌抓牌,把牌按大小插入。
需要注意的地方是
不要加多余的判断,否则会超时;第一次运行的时候,我在里面的while循环条件判断上加了一句 pre != curr,结果就报超时了。
check一下逻辑,发现完全是无用判断浪费时间,去掉后就通过了。