面试中常见链表问题9:对单链表进行插入排序

来源:互联网 发布:网络及信息安全答案 编辑:程序博客网 时间:2024/06/05 03:47
给定一个单链表,对该链表进行插入排序。
ListNode* insertionSortList(ListNode* head) {if (head == NULL || head->next == NULL)return head;ListNode *pHead = new ListNode(INT_MAX);pHead->next = head;ListNode *tail = head;ListNode *pre = pHead;ListNode *cur = head->next;tail->next = NULL;while (cur){if (cur->val >= tail->val){tail->next = cur;tail = tail->next;cur = cur->next;tail->next = NULL;continue;}while (pre->next != tail && pre->next->val < cur->val){pre = pre->next;}ListNode *tmp = cur;cur = cur->next;tmp->next = pre->next;pre->next = tmp;pre = pHead;}return pHead->next;}
0 0