最后更新于
这有帮助吗?
这有帮助吗?
插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。
插入排序算法:
插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
重复直到所有输入数据插入完为止。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
ans = ListNode(float("-inf"))
# do domething
return ans.nextclass Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
ans = ListNode(float("-inf"))
def insert(to_be_insert):
# 选择插入的位置,并插入
while head:
insert(head)
head = head.next
return ans.next# ans 就是上面我提到的虚拟节点
ans = cur
while cur.next and cur.next.val < to_be_insert.val:
cur = cur.nextto_be_insert.next = cur.next
cur.next = to_be_insertclass Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
ans = ListNode(float("-inf"))
def helper(inserted):
cur = ans
while cur.next and cur.next.val < inserted.val:
cur = cur.next
inserted.next = cur.next
cur.next = inserted
while head:
helper(head)
head = head.next
return ans.nextinserted.next = cur.next
cur.next = insertedclass Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
ans = ListNode(float("-inf"))
def insert(to_be_insert):
# 选择插入的位置,并插入
# 这里 to_to_insert 的 next 会被修改,进而影响外层的 head
while head:
# 留下联系方式
next = head.next
insert(head)
# 使用联系方式更新 head
head = next
return ans.next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
ans = ListNode(float("-inf"))
while head:
next = head.next
cur = ans
while cur.next and cur.next.val < head.val:
cur = cur.next
head.next = cur.next
cur.next = head
head = next
return ans.nextclass Solution {
public ListNode insertionSortList(ListNode head) {
ListNode ans = new ListNode(-1);
while( head != null ){
ListNode next = head.next;
ListNode cur = ans;
while(cur.next != null && cur.next.val < head.val ){
cur = cur.next;
}
head.next = cur.next;
cur.next = head;
head = next;
}
return ans.next;
}
}var insertionSortList = function (head) {
ans = new ListNode(-1);
while (head != null) {
next = head.next;
cur = ans;
while (cur.next != null && cur.next.val < head.val) {
cur = cur.next;
}
head.next = cur.next;
cur.next = head;
head = next;
}
return ans.next;
};class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode dummy, *p;
while (head) {
auto *n = head;
head = head->next;
p = &dummy;
while (p->next && p->next->val < n->val) p = p->next;
n->next = p->next;
p->next = n;
}
return dummy.next;
}
};