LeetCode OJ 编程题: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) {
if((head == NULL) || (head->next == NULL))
return head;
ListNode *p, *pre_q, *q, *temp;
p = head->next;
head->next = NULL;
while(p != NULL)
{
pre_q = q = head;
//q = head->next;
while((q != NULL) && (q->val <= p->val))
{
pre_q = q;
q = q->next;
}
//当头结点的值大于要比较的结点时
if((q == head) && (q->val > p->val))
{
temp =p;
p = p->next;
temp->next = head;
head = temp;
}
else
{
temp = p;
p = p->next;
pre_q->next = temp;
temp->next = q;
}
}
return head;
}
};