您的位置:首页 > 其它

LeetCode(147) Insertion Sort List

2015-08-09 22:13 483 查看
[code]/**
 * 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)

            return NULL;

        if(head->next == NULL)

            return head;

        ListNode *newHead = new ListNode(0);
        newHead->next = head;

        ListNode *p1Pre = head;
        ListNode *p1 = head->next;

        while(p1) {

            ListNode *p2 = newHead;
            ListNode *p3 = newHead->next;
            while(p3 != p1) {

                if(p3->val > p1->val)

                    break;

                p2 = p3;
                p3 = p3->next;

            }

            if(p3 == p1) {

                p1Pre = p1;
                p1 = p1->next;
                continue;

            }

            p1Pre->next = p1->next;

            p2->next = p1;
            p1->next = p3;

            p1 = p1Pre->next;

        }

        return newHead->next;

    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: