一【题目类别】
二【题目难度】
三【题目编号】
四【题目描述】
- 对链表进行插入排序。
- 注:插入排序的动画演示gif暂时出了一点问题,后续会补充上,读者可以百度一下插入排序的主要思想,我想大家应该都明白
- 插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。 - 插入排序算法:
- 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
- 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
- 重复直到所有输入数据插入完为止。
五【题目示例】
- 示例 1:
输入: 4->2->1->3
输出: 1->2->3->4 - 示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
六【解题思路】
- 这种题肯定要设置一个pre前驱指针方便指针的链接和删除,所以pre指向头部位置,然后循环整个链表,挨个比较,如果两两之间有序,那么指针后移,如果两两之间无序,pre前驱指针从头开始向后找插入位置,然后插入即可,有个小细节就是要先把待插入指针的后继指针连接到head指针,否则pre的后继指针连接到待插入结点就无法给当前结点的后继结点链接了
七【时间频度】
- 时间复杂度:
O
(
N
2
)
O(N^2)
O(N2)
八【代码实现】
- Java语言版
package LinkedList;
public class p147_InsertionSortList {
int val;
p147_InsertionSortList next;
p147_InsertionSortList(int x) {
this.val = x;
}
public static void main(String[] args) {
p147_InsertionSortList num1 = new p147_InsertionSortList(4);
p147_InsertionSortList num2 = new p147_InsertionSortList(2);
p147_InsertionSortList num3 = new p147_InsertionSortList(1);
p147_InsertionSortList num4 = new p147_InsertionSortList(3);
num1.next = num2;
num2.next = num3;
num3.next = num4;
p147_InsertionSortList res = insertionSortList(num1);
while (res != null) {
System.out.print(res.val + " ");
res = res.next;
}
}
public static p147_InsertionSortList insertionSortList(p147_InsertionSortList head) {
if (head == null || head.next == null) {
return head;
}
p147_InsertionSortList newHead = new p147_InsertionSortList(Integer.MIN_VALUE);
newHead.next = head;
p147_InsertionSortList cur = head;
p147_InsertionSortList pre = newHead;
while (cur != null) {
if (cur.val < pre.val) {
p147_InsertionSortList newIndex = newHead.next;
p147_InsertionSortList newPre = newHead;
while (newIndex != pre && newIndex.val < cur.val) {
newIndex = newIndex.next;
newPre = newPre.next;
}
pre.next = cur.next;
cur.next = newIndex;
newPre.next = cur;
cur = pre.next;
}
else {
cur = cur.next;
pre = pre.next;
}
}
return newHead.next;
}
}
- C语言版
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode* insertionSortList(struct ListNode* head)
{
if (head == NULL || head->next == NULL)
{
return head;
}
struct ListNode* newHead = (struct ListNode*)malloc(sizeof(struct ListNode));
newHead->next = head;
struct ListNode* cur = head->next;
struct ListNode* pre = newHead->next;
while (cur != NULL)
{
if (cur->val < pre->val)
{
struct ListNode* newIndex = newHead->next;
struct ListNode* newPre = newHead;
while (newIndex != pre && newIndex->val < cur->val)
{
newIndex = newIndex->next;
newPre = newPre->next;
}
pre->next = cur->next;
cur->next = newIndex;
newPre->next = cur;
cur = pre->next;
}
else
{
cur = cur->next;
pre = pre->next;
}
}
return newHead->next;
}
九【提交结果】
- Java语言版
- C语言版