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) {
ListNode *search, *last, *next;
if(head == NULL)
return head;
last = head;
while(last->next != NULL)
{
next = last->next;
if(next->val >= last->val)
last = last->next;
else
{
if(next->val <= head->val)
{
last->next = next->next;
next->next = head;
head = next;
}
else
{
search = head;
while(next->val > search->next->val)
search = search->next;
last->next = next->next;
next->next = search->next;
search->next = next;
}
}
}
return head;
}
};