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;
    }
  • 相关阅读:
    oracle lengthb
    layui-rp
    1709052基于框架新建 子项目
    echar 常用单词
    Leetcode 481.神奇字符串
    Leetcode 480.滑动窗口中位数
    Leetcode 479.最大回文数乘积
    Leetcode 477.汉明距离总和
    Leetcode 476.数字的补数
    Leetcode 475.供暖气
  • 原文地址:https://www.cnblogs.com/zhuangzebo/p/3985279.html
Copyright © 2011-2022 走看看