首页 > 其他 > 详细

[LeetCode] 147 Insertion Sort List

时间:2015-03-12 14:44:17      阅读:286      评论: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 *e=new ListNode(0);
        ListNode *p,*pre,*prenext,*tail;
        p=head;
        //连接第一个点
        e->next=p;
        p=p->next;
        tail=e->next;
        tail->next=NULL;
        while(p!=NULL)
        {
            if(tail->val>p->val)//需要插入
            {
                pre=e;
                while(pre->next->val<=p->val&&pre->next!=NULL)
                    pre=pre->next;
                prenext=pre->next;
                pre->next=p;
                p=p->next;
                pre->next->next=prenext;
            }
            else                //尾部接入
            {
                tail->next=p;
                p=p->next;
                tail=tail->next;
                tail->next=NULL;
            }
        }
        return e->next;
    }
};

[LeetCode] 147 Insertion Sort List

原文:http://www.cnblogs.com/aorora/p/4332061.html

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