现在的位置: 首页 > 综合 > 正文

[LeetCode] Insertion Sort List

2018年04月26日 ⁄ 综合 ⁄ 共 483字 ⁄ 字号 评论关闭

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)
            return NULL;
        ListNode *dumy = new ListNode(-1);
        dumy->next = head;
        ListNode *p = head->next;
        head->next = NULL;
        while(p)
        {
            ListNode *pNext = p->next;
            ListNode *q = dumy;
            while(q->next && q->next->val < p->val)
                q = q->next;
            p->next = q->next;
            q->next = p;
            p = pNext;
        }
        p = dumy->next;
        delete dumy;
        return p;
    }
};

抱歉!评论已关闭.