147. Insertion Sort List
题目
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) {}
* };
*/
// insertion sort list
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
//思路:新建一个链表, 遍历原链表,将每个节点加入新链表正确的位置
ListNode* dummy = new ListNode(0);
ListNode* cur = head; //原链表当前位置
ListNode* next = NULL; //记录原链表下一节点
ListNode* pre = dummy; //新链表需要比较的前后节点
while (cur)
{
next = cur->next;
while (pre->next&& pre->next->val < cur->val)
{
pre = pre->next;
}
cur->next = pre->next; //将当前节点独立出来
pre->next = cur;
pre = dummy; //回到起点
cur = next; //处理下一个节点
}
return dummy->next;
}
};