积少成多

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Sort a linked list using insertion sort.

============

思路:

怎么判断链表开始?   怎么判断链表结束?

定义dummy假的头节点,这样的话直接就有了链表头dummy.next

怎么将curr指向的节点插入到in指向的位置?

  四步就可以完成:ListNode *tmp = curr->next;//保存curr下一节点

          curr->next = in->next;//将curr节点接到in的下一位置,后指

          in->next = curr;//完成前指

          curr = tmp;//更新curr

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *findLocationInsert(ListNode *head,int x){
        for(;head->next;head = head->next){
            if(head->next->val >= x) break;
        }
        return head;
    }
    ListNode *insertionSortList(ListNode* head) {
        if(head==nullptr || head->next==nullptr) return head;
        ListNode dummy(-1);
        ListNode *curr,*in;
        curr = head;
        for(;curr;){
            in = &dummy;
            in = findLocationInsert(in,curr->val);
            ListNode *tmp = curr->next;
            curr->next = in->next;
            in->next = curr;
            curr = tmp;
        }
        return dummy.next;
    }
};

 

posted on 2016-06-22 15:15  x7b5g  阅读(162)  评论(0编辑  收藏  举报