Sort a linked list using insertion sort.
此题较简单,就是练习链表增删查问题
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(NULL == head || NULL==head->next) return head;
ListNode *p = head->next, *q, *trace,*pre, *curPre = head;
while(p){
trace = head;
pre = NULL;
q = p->next;
while(trace != p){
//从头节点开始查找节点值是否有比当前节点p值大的
if(trace->val > p->val){
if(NULL == pre){
curPre->next = p->next;
p->next = head;
head = p;
break;
}
curPre->next = p->next;
p->next = pre->next;
pre->next = p;
break;
}
pre = trace;
trace = trace->next;
}
//如果p节点被插入到前面的节点中
if(trace != p){
p = q;
}
else{
curPre = p;
p=p->next;
}
}
return head;
}
};