您的位置:首页 > 其它

[leetcode147]insertion sort list

2017-05-08 15:08 471 查看
解题思路:两个指针,一个指针的下一个与另一个指针的下一个做交换操作,先给后拿的思想

# 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

        """

        if not head:

            return head

        dummy=ListNode(0)

        dummy.next=head

        while head and head.next:

            if head.val<=head.next.val:

                head=head.next

            else:

                cur=dummy

                while cur.next.val<head.next.val:

                    cur=cur.next

                tmp=head.next

                head.next=tmp.next

                tmp.next=cur.next

                cur.next=tmp
        return dummy.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: