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;
// Define the new head
ListNode *newHead = new ListNode(-1);
int length = 0;
while(head != NULL) {
int location = 0;
auto prenode = newHead;
auto tempnode = newHead->next;
while(tempnode != NULL) {
if(tempnode->val > head->val)
{
break;
}
prenode = tempnode;
tempnode = tempnode->next;
}
auto cur = head->next;
prenode->next = head;
head->next = tempnode;
head = cur;
}
return newHead->next;
}
};