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

leetcode_num179_Insertion Sort list

时间:2015-04-01 23:56:33      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   排序算法   

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||!head->next)
            return head;
        ListNode *pNode=new ListNode(10000);// record the position of head
        pNode->next=head;
        ListNode *spNode=pNode;
        ListNode* bpNode=head;
        while(bpNode->next){
            if(bpNode->next->val<bpNode->val){
                ListNode*cpNode=bpNode->next;
                bpNode->next=bpNode->next->next;
                while(spNode!=bpNode){
                    if(spNode->next->val>cpNode->val){
                        cpNode->next=spNode->next;
                        spNode->next=cpNode;
                        break;
                    }
                    else
                        spNode=spNode->next;
                }
                spNode=pNode;
            }
            else
                bpNode=bpNode->next;
        }
        return pNode->next;
    }
};


leetcode_num179_Insertion Sort list

标签:c++   leetcode   排序算法   

原文地址:http://blog.csdn.net/eliza1130/article/details/44814499

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