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 *sortedHead = new ListNode(-1);
while(head != NULL) {
//保存head
ListNode *temp = head->next;
ListNode *cur = sortedHead;
while(cur->next != NULL && cur->next->val < head->val)
{
cur = cur->next;
}
//插入
head->next = cur->next;
cur->next = head;
//恢复head
head = temp;
}
return sortedHead->next;
}
};
链表初始化有些忘记了,回头又看了一下