zoukankan      html  css  js  c++  java
  • 单向链表

    #include <iostream>
    #include <limits>
    #include <vector>
    using   namespace   std;
    
    struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
                val(x), next(NULL) {
        }
    };
    
    class Solution {
    public:
        ListNode* Create(vector<int> da) {
            if (da.empty()) return NULL;
            ListNode* head = new ListNode(da[0]);
            ListNode* cur  = head;
            for (int i=1; i<da.size(); ++i) {
                ListNode* a = new ListNode(da[i]);
                cur->next = a;
                cur = cur->next;
            }
            return head;
        }
        void PrintList(ListNode* head) {
            while(head) {
                std::cerr << head->val << " ";
                head = head->next;
            }
            std::cerr << std::endl;
        }
        ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
        {
            if (!pHead1) return pHead2;
            if (!pHead2) return pHead1;
            ListNode* head = pHead1;
            ListNode* per = NULL;
            ListNode* net = NULL;
            while (pHead1 && pHead2) {
                if (pHead1->val <= pHead2->val) {
                    per = pHead1;
                    pHead1 = pHead1->next;
                } else {
                    net = pHead2->next;
                    per->next = pHead2;
                    pHead2->next = pHead1;
                    pHead2 = net;
                }
            }
            if (!pHead1) per->next = pHead2;
            return head;
        }
        ListNode* ReverseList(ListNode* head) {
            if (head == NULL) {
                return NULL;
            }
            ListNode *per = NULL, *cur = head, *net = head->next;
            while (net != NULL) {
                cur->next = per;
                per = cur;
                cur = net;
                net = cur->next;
            }
            cur->next = per;
            return cur;
        }
    };
    
    int  main()
    {
        vector<int> da{1,3,5};
        vector<int> db{2,4,6};
        Solution s;
        ListNode* head1 = s.Create(da);
        ListNode* head2 = s.Create(db);
        s.PrintList(head1);
        s.PrintList(head2);
        s.PrintList(s.Merge(head1, head2));
        s.PrintList(s.ReverseList(head2));
        return 0;
    }
    
    
    
  • 相关阅读:
    poj 2425 AChessGame(博弈)
    poj2975 Nim 胜利的方案数
    hdu 5724 SG+状态压缩
    hdu 5274 Dylans loves tree(LCA + 线段树)
    hdu 5266 pog loves szh III(lca + 线段树)
    hdu 4031 attack 线段树区间更新
    51 nod 1188 最大公约数之和 V2
    51nod 1040 最大公约数之和(欧拉函数)
    51nod 1035:最长的循环节
    Nim游戏(组合游戏Combinatorial Games)
  • 原文地址:https://www.cnblogs.com/narjaja/p/10697227.html
Copyright © 2011-2022 走看看