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

leetcode - [5]Insertion Sort List

时间:2014-09-22 03:01:31      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   div   sp   on   

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;
}

 

leetcode - [5]Insertion Sort List

标签:style   blog   color   io   os   ar   div   sp   on   

原文地址:http://www.cnblogs.com/zhuangzebo/p/3985279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!