码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode]85. Insertion Sort List链表插入排序

时间:2015-11-16 14:08:07      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

Sort a linked list using insertion sort.

 

Subscribe to see which companies asked this question

 

解法:设置3个指针:应插入位置的前一个节点first、当前处理节点third和其前一个节点second,设置辅助节点help指向头节点。然后从头节点的next节点开始遍历,一个个插入正确位置即可。注意在插入到新位置之前需要链接好second和third->next,防止链表断开。

/**
 * 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;
        ListNode* help = new ListNode(0);
        help->next = head;
        ListNode *second = head, *third = head->next;
        while (third != NULL) {
            ListNode* first = help;
            if (third->val < second->val) {
                while (first->next->val <= third->val) // 找到插入点
                    first = first->next;
                second->next = third->next; // 链接断开点
                third->next = first->next; // 插入到新的位置
                first->next = third;
                third = second->next; // 前移一个节点
            }
            else { // 前移一个节点
                second = third;
                third = third->next;
            }
        }
        return help->next;
    }
};

 

[LeetCode]85. Insertion Sort List链表插入排序

标签:

原文地址:http://www.cnblogs.com/aprilcheny/p/4968474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!