【LEETCODE】147- Insertion Sort List [Python]

来源:互联网 发布:linux下的怎么写程序 编辑:程序博客网 时间:2024/05/22 13:01

Sort a linked list using insertion sort.


题意:

用插入排序


参考:

http://bookshadow.com/weblog/2015/01/06/leetcode-insertion-sort-list/



Python:

# 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        """                if head is None or head.next is None:            return head                dummy=ListNode(0)        dummy.next=head        cur=head                while cur.next:                        if cur.val>cur.next.val:                            pre=dummy                while pre.next.val<cur.next.val:                    pre=pre.next                m=cur.next                cur.next=m.next                m.next=pre.next                pre.next=m            else:                cur=cur.next                return dummy.next                                




0 0