题意:用链表实现插入排序。
思路:简单模拟,注意处理链表的开头与结尾。
/**
* 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) {
if(!head) return head;
ListNode* next = head->next;
head->next = NULL;
while(next) {
auto tempnext = next->next;
next->next = NULL;
auto start = head;
if(start->val >= next->val) {
next->next = head;
head = next;
next = tempnext;
continue;
}
while(start) {
if(start->next == NULL) {
start->next = next;
break;
}
if(next->val <= start->next->val) {
next->next = start->next;
start->next = next;
break;
}
start = start->next;
}
next = tempnext;
}
return head;
}
};