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 newstart(INT_MIN);
for(auto cur=head;cur!=NULL;)
{
ListNode *p=&newstart;
while(p->next!=NULL&&cur->val > p->next->val)
p=p->next;
ListNode *temp=p->next;
p->next=cur;
cur=cur->next;
p->next->next=temp;
}
return newstart.next;
}
};