首页 > 其他 > 详细

LeetCode----Insertion sort list

时间:2014-02-17 04:30:45      阅读:334      评论:0      收藏:0      [点我收藏+]


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* insertionSortList(ListNode *list)
    {
        ListNode *new_list(NULL), *next(NULL);
        while(list)
        {
            next = list->next;
            new_list = InsertNode(new_list, list);
            list = next;
        }
        return new_list;
    }
private:
    ListNode* InsertNode(ListNode *list, ListNode *node)
    {
        //insert node into a sorted list
        ListNode *pre(NULL), *cur(list);
        while(cur && cur->val < node->val)
        {
            pre = cur;
            cur = cur->next;
        }
        if(pre == NULL){
            node->next = cur;
            return node;
        }
        else{
            node->next = cur;
            pre->next = node;
        }
        return list;
    }
};


LeetCode----Insertion sort list

原文:http://blog.csdn.net/shoulinjun/article/details/19290271

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