Sort a linked list using insertion sort.
思考:画图帮助理解,考虑以下情况:空链表,单结点链表,两个结点(第二个结点大于或小于第一个),多个结点。
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ListNode *p,*q,*r;
p=head;
if(!head) return NULL;
while(p->next)
{
q=p->next; //q当前待移动结点
r=head; //r-p已排序
while(r->next->val<q->val&&r!=p)
r=r->next;
if(r==p&&r->val<=q->val)
{
p=p->next;
}
else if(r==p)
{
r->next=q->next;
q->next=r;
head=q;
}
else if(r->val>q->val)
{
p->next=q->next;
q->next=r;
head=q;
}
else
{
p->next=q->next;
q->next=r->next;
r->next=q;
}
}
return head;
}
};