题干
![]()
获取题源请点击https://leetcode.cn/problems/insertion-sort-list/description/?languageTags=c
思路
插入排序 利用直接插入排序的算法思想,单链表无法向前遍历,需要通过三个指针完成操作。
- 时间复杂度:O(n²),n为链表长度。
- 空间复杂度:O(1)。
C代码
感谢LeetCode用户꧁MxQuan.꧂提供的思路。
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 31 32 33
|
struct ListNode* insertionSortList(struct ListNode* head){ if(head == NULL) return NULL; struct ListNode* L = (struct ListNode*)malloc(sizeof(struct ListNode)); L->next = head; struct ListNode *cur = head->next, *pre = head, *tmp;
while(cur != NULL){ if(cur->val >= pre->val){ cur = cur->next; pre = pre->next; }else{ tmp = L; while(tmp->next->val < cur->val) tmp = tmp->next; pre->next = cur->next; cur->next = tmp->next; tmp->next = cur; cur = pre->next; } }
return L->next; }
|
题目答案
特别地,由于408考试所用链表大多数为带头结点的链表,且结点结构不一致,因此最后写出的代码略有不同,但思路一致。
手写版
![]()