码迷,mamicode.com
首页 > 其他好文 > 详细

Insertion Sort List

时间:2014-12-03 11:57:51      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   on   div   log   

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

标签:style   blog   io   color   sp   for   on   div   log   

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

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