zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    hdu 1269 迷宫城堡(强联通分量,基础)
    hdu 2102 A计划(BFS,基础)
    python 变量命名规范
    rpm常用选项
    memcached
    session共享
    Nginx高级使用
    nginx 反向代理
    Nginx基本使用
    github 建立博客
  • 原文地址:https://www.cnblogs.com/zhuangzebo/p/3985279.html
Copyright © 2011-2022 走看看