难度:中等。
标签:链表,排序。
正确解法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* sortedhead = head;
ListNode* sortedtail = head;
ListNode* cur = head->next;
while(cur != nullptr){
ListNode* sorted = sortedhead;
ListNode* lastSorted = nullptr;
while(sorted != cur){
if(sorted->val > cur->val){
break;
}
lastSorted = sorted;
sorted = sorted->next;
}
if(lastSorted == sortedtail){
sortedtail = cur;
cur = cur->next;
continue;
}
ListNode* next = cur->next;
sortedtail->next = next;
if(lastSorted == nullptr){
cur->next = sortedhead;
sortedhead = cur;
}
else{
cur->next = lastSorted->next;
lastSorted->next = cur;
}
cur = next;
}
return sortedhead;
}
};
结果: