LeetCode Insertion Sort List

来源:互联网 发布:无法打开awrrpt.sql 编辑:程序博客网 时间:2024/05/16 12:26

LeetCode解题之Insertion Sort List


原题

通过插入排序的方法排序一个链表。

注意点:

例子:

解题思路

数组的插入排序很简单,将元素依次放入已经排好序的数组中的正确位置。链表与数组的操作稍微有些不同,数组是将比要插入的元素大的数值往后移,直到遇到比该元素小的值,就把该元素放在比它小的值后面。但单链表只能从头开始判断新的节点该插入到哪里。链表也可以根据尾节点进行优化,如果要插入的节点比尾节点还大的话,就不用从头开始找插入的位置了。插入时要注意链表插入操作,Python写链表相关操作还是很方便的。

AC源码

# Definition for singly-linked list.class ListNode(object):    def __init__(self, x):        self.val = x        self.next = Noneclass Solution(object):    def insertionSortList(self, head):        """        :type head: ListNode        :rtype: ListNode        """        dummy = ListNode(-1)        cur = dummy        while head:            # check if it is needed to reset the cur pointer            if cur and cur.val > head.val:                cur = dummy            # find the place to insert            while cur.next and cur.next.val < head.val:                cur = cur.next            # insert and sort the next element            cur.next, cur.next.next, head = head, cur.next, head.next        return dummy.nextif __name__ == "__main__":    None

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

0 0
原创粉丝点击