AC代码1
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if(head==NULL || head->next==NULL)
return head;
ListNode* pCur = head;
ListNode* cur = head->next;
ListNode* p =NULL;
ListNode* q = head;
while(cur){
p = NULL, q = head;
while(q && q!=cur &&q->val <= cur->val){
p = q;
q = q->next;
}
if(cur==q){
pCur = cur;
cur = cur->next;
}else{
if(p){
p->next = cur;
}else{
head = cur;
}
pCur->next = cur->next;
cur->next = q;
// 将当前元素放到正确位置后,开始处理下一个元素
cur = pCur->next;
}
}
return head;
}
};
第二种思路
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode *dummy = new ListNode(-1), *cur = dummy;
while (head) {
ListNode *t = head->next;
cur = dummy;
while (cur->next && cur->next->val <= head->val) {
cur = cur->next;
}
head->next = cur->next;
cur->next = head;
head = t;
}
return dummy->next;
}
};