LeetCode 147. Insertion Sort List - 链表(Linked List)系列题18

Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.

The steps of the insertion sort algorithm:

  1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
  3. It repeats until no input elements remain.

The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.

Example 1:

Input: head = [4,2,1,3]
Output: [1,2,3,4]

Example 2:

Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]

Constraints:

  • The number of nodes in the list is in the range [1, 5000].
  • -5000 <= Node.val <= 5000

题目指定要用插入排序法对链表进行排序。这跟数组的插入排序法的思路差不多。从链表头到尾依次处理每个节点,对于一个正要处理的当前节点(表示它前面的节点已经处理完成是排好序的),要做的是找到在它之前可以插入的位置。为了方便定义一个新的节点作为当前节点之前已排好序的节点的伪头节点。现在要从已排好序的节点中寻找可插入的位置也就是找到最后一个比当前节点值小的节点,用另外一个指针pre从伪头节点开始依次比较pre.next的值和当前节点值,当第一次出现pre.next大于等于当前节点值时,那么pre和pre.next就是要插入的位置。(如果一直没找到就插入到最后,pre就是最后节点pre.next为空,插入位置同样也是pre和pre.next之间)。完成插入之后,当前节点就可以更新为下一个节点继续做插入操作,直到最后。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head
        
        preHead = ListNode(-1)
        cur = head
        while cur:
            pre = preHead
            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 preHead.next

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值