147. insertion sort list



  1. Insertion Sort List:题目链接

方法1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
struct ListNode* (struct ListNode* head){
struct ListNode* dummyHead = (struct ListNode*)malloc(sizeof(struct ListNode));
dummyHead->next = head;
if (head == NULL) {
return head;
}
struct ListNode* pre = NULL;
struct ListNode* cur = head;
struct ListNode* next = NULL; // next:待排序节点
while (cur->next != NULL) {
next = cur->next;
if (cur->val <= next->val) { // 待排序节点 >= 前面节点 说明有序 遍历下一个
cur = cur->next;
}else{
pre = dummyHead;
while (pre->next != NULL && pre->next->val <= next->val) { // 从链表头开始 找到待排节点要插入位置的前驱
pre = pre -> next;
}
// 找到前驱 开始插入
cur->next = next->next;
next->next = pre->next;
pre->next = next;
}
}
return dummyHead->next;
}

/*
Runtime: 4 ms, faster than 100.00% of C online submissions for Insertion Sort List.
*/