[leetcode] 147. Insertion Sort List
Description
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Algorithm of Insertion Sort:
Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
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.
It repeats until no input elements remain.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
分析
题目的意思是:用插入排序来对链表排序。
- 这里用到了一个trick,用了额外变量dummy来实现,这样我们在处理头结点的时候就方便多了。
cpp代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* dummy=new ListNode(-1);
ListNode* cur;
while(head){
ListNode* t=head->next;
cur=dummy;
while(cur->next&&cur->next->val<head->val){
cur=cur->next;
}
head->next=cur->next;
cur->next=head;
head=t;
}
return dummy->next;
}
};
Python实现
下面是python的实现,也是借助了dummy的空节点:
# 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]:
dummy = ListNode()
curr = head
while curr:
next_p = curr.next
prev = dummy
while prev.next and prev.next.val < curr.val:
prev = prev.next
curr.next = prev.next
prev.next = curr
curr = next_p
return dummy.next
参考文献
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)