leetcode

Sort a linked list using insertion sort.

思路:插入排序

#include <iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x): val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        if (!head || head->next == NULL) {
            return head;
        }

        ListNode *cur, *prev, *next, *p;

        cur = head->next;
        head->next = NULL;        

        while (cur) {
            p = head;
            prev = NULL;

            while ((p != NULL) && (p->val < cur->val)) {
                prev = p;
                p = p->next;
            } 

            next = cur->next;
            if (p != NULL) {
                if (prev != NULL) {
                    cur->next = p;
                    prev->next = cur;
                }
                else {
                    cur->next = p;
                    head = cur;
                }
            } else {
                cur->next = NULL;    
                prev->next = cur;
            }
            cur = next;
        }
        return head;
    }
};

int main(int argc, char *argv[]) {
    ListNode *p = new ListNode(4);
    p->next = new ListNode(0);
    p->next->next = new ListNode(-1);
    p->next->next->next = new ListNode(-1);

    Solution *solution = new Solution();
    p = solution->insertionSortList(p);

    while (p) {
        cout << p->val << endl;
        p = p->next;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zhuangzebo/p/3985279.html