编程语言
首页 > 编程语言> > 排序算法-Leetcode-147

排序算法-Leetcode-147

作者:互联网

0️⃣python数据结构与算法学习路线
学习内容:

  • 基本算法:枚举、排序、搜索、递归、分治、优先搜索、贪心、双指针、动态规划等…
  • 数据结构:字符串(string)、列表(list)、元组(tuple)、字典(dictionary)、集合(set)、数组、队列、栈、树、图、堆等…

题目:

从第一个元素开始,该链表可以被认为已经部分排序。每次迭代时,从输入数据中移除一个元素,并原地将其插入到已排好序的链表中。

输入输出:

输入: 4->2->1->3
输出: 1->2->3->4

解题思路:

算法实现:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def insertionSortList(self, head):
        dummy = ListNode(0)
        cur = head
        while cur:
            pre = dummy
            while pre.next and pre.next.val <= cur.val:
                pre = pre.next
            tmp = cur.next
            cur.next = pre.next
            pre.next = cur
            cur = tmp
        return dummy.next

出现问题:

标签:pre,147,val,self,next,算法,排序,Leetcode
来源: https://blog.csdn.net/weixin_42802447/article/details/115269668