147链表插入排序 Posted on 2020-04-19 Words count in article: 261 | Reading time ≈ 1 147.链表插入排序下面是题目下面是题目给出的模板1234567891011121314/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* insertionSortList(ListNode* head) { }}; 下面是对一个优质解答的分析1234567891011121314151617181920212223242526272829303132class Solution {public:ListNode* insertionSortList(ListNode* head) { if (!head || !head->next) return head; ListNode *dummyhead = new ListNode(-1);//伪头指针 dummyhead->next = head; ListNode *prev = head; ListNode *node = head->next; while (node) { if (node->val < prev->val) { ListNode* temp = dummyhead;//!!temp要等于dummyhead,这样才可以比较第一个元素 while (temp->next->val < node->val)//!!!这里是temp->next:因为要修改前面的temp的指向 { temp = temp->next;//指针后移 } prev->next = node->next; node->next = temp->next; temp->next = node; node = prev->next;//此时不用改变prev指向!因为prev没有变,只是待排序元素变了位置。 } else { prev = prev->next; node = node->next; } } return dummyhead->next;//!!!不能返回head!!因为后面会改变head所指向内存的位置!}}; -------------本文结束,感谢您的阅读------------- Post author: Jason Post link: https://jasonxqh.github.io/2020/04/19/147%E9%93%BE%E8%A1%A8%E6%8F%92%E5%85%A5%E6%8E%92%E5%BA%8F/ Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.