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

[LeetCode] 147 Insertion Sort List

时间:2015-03-12 14:46:30      阅读:155      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!