[LeetCode] 147 Insertion Sort List

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)