美文网首页
python实现leetcode之147. 对链表进行插入排序

python实现leetcode之147. 对链表进行插入排序

作者: 深圳都这么冷 | 来源:发表于2021-10-17 00:22 被阅读0次

解题思路

使用一个虚拟节点作为头节点,代码会被极大的优化

147. 对链表进行插入排序

代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def insertionSortList(self, head: ListNode) -> ListNode:
        rtv = ListNode(0)
        while head:
            nx = head.next
            pt = rtv
            while pt.next and pt.next.val < head.val:
                pt = pt.next
            head.next = pt.next
            pt.next = head
            head = nx
        return rtv.next
效果图

相关文章

网友评论

      本文标题:python实现leetcode之147. 对链表进行插入排序

      本文链接:https://www.haomeiwen.com/subject/lfvuoltx.html