Sort a linked list using insertion sort.
插入排序,仿照数组的插入排序,对于节点p,从head开始到p前一个节点,与每个节点进行比较,如果小于这个节点,则插入到这个节点之前。注意插入前要删除节点p及因为删除而造成的链表的改动。
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head==NULL)return NULL;
ListNode *p,*q;
p=head;q=head->next;
while(q){
ListNode *temp=head;
if(temp->val>q->val){
p->next=q->next;
head=q;
q->next=temp;
q=p->next;
}else{
while(temp->next!=q){
if(temp->next->val>q->val){
p->next=q->next;
q->next=temp->next;
temp->next=q;
q=p->next;
break;
}
temp=temp->next;
}
if(temp->next==q){
p=p->next;
q=q->next;
}
}
}
return head;
}
};