首页 > 其他 > 详细

Insertion Sort List Leetcode

时间:2015-12-22 22:48:28      阅读:197      评论:0      收藏:0      [点我收藏+]

Sort a linked list using insertion sort.

这个题我巧妙的设置了一个临时头结点

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if (head == nullptr)
        return head;
        ListNode temp(0);
        temp.next = head;
        head = &temp;
        ListNode *cur = head->next;
        while (cur->next != nullptr)
        {
            ListNode *back = head;
            while (back->next != cur->next && back->next->val <= cur->next->val)
                back = back->next;
            if (back->next != cur->next)
            {
                ListNode *now = cur->next;
                cur->next = cur->next->next;
                now->next = back->next;
                back->next = now;
            }
            else {
                cur = cur->next;
            }    
        }
        return temp.next;
    }
};

 

Insertion Sort List Leetcode

原文:http://www.cnblogs.com/sdlwlxf/p/5068241.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!