首页 > 其他 > 详细

leetcode_num179_Insertion Sort list

时间:2015-04-01 23:54:25      阅读:343      评论: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||!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

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

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