问题描述如下:
Sort a linked list using insertion sort.
cpp代码如下:
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head==NULL||head->next==NULL)return head;
ListNode node(0);
node.next=head;
ListNode* p=head->next,*r=head;
while(p){
ListNode* q=&node;
for(;q->next!=p&&q->next->val<p->val;q=q->next);
if(q->next==p){
r=p;
p=p->next;
}
else{
r->next=p->next;;
p->next=q->next;
q->next=p;
p=r->next;
}
}
return node.next;
}
};