首页 > 其他 > 详细

Insertion Sort List

时间:2014-12-03 11:56:17      阅读:264      评论:0      收藏:0      [点我收藏+]

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) {}
 * };
 */
class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        if(head == NULL || head->next == NULL) return head;
        
        ListNode *point = new ListNode(0);
        ListNode *iter, *tmp, *hold, *prev, *newhead;
        point->next = head;
        newhead = head->next;
        head->next = NULL;
        
        while(newhead){
            tmp = newhead;
            hold = point;
            while(hold->next && hold->next->val <= tmp->val){
                hold = hold->next;
            }
            newhead = newhead->next;
            tmp->next = hold->next;
            hold->next = tmp;
        }
        return point->next;
    }
};

 

Insertion Sort List

原文:http://www.cnblogs.com/code-swan/p/4139611.html

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