zoukankan      html  css  js  c++  java
  • 合并两个排序的链表

    题目描述

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <vector>
    #include <cmath>
    #include <algorithm>
    using namespace std;
    
    struct ListNode
    {
        int val;
        struct ListNode *next;
        ListNode(int x):val(x),next(NULL){}
    };
    
    class Solution
    {
    public:
        ListNode* Merge(ListNode* pHead1,ListNode* pHead2)
        {
            if(pHead1==NULL)
                return pHead2;
            if(pHead2==NULL)
                return pHead1;
            ListNode* mergeHead=pHead1;
    
            if(pHead1->val<pHead2->val)
            {
                mergeHead=pHead1;
                mergeHead->next=Merge(pHead1->next,pHead2);
            }
            else
            {
                mergeHead=pHead2;
                mergeHead->next=Merge(pHead1,pHead2->next);
            }
    
            return mergeHead;
        }
    };
    
    int main()
    {
        Solution s;
        int n;
        struct ListNode *mergeHead=NULL;
        struct ListNode *pHead1=NULL;
        struct ListNode *pHead2=NULL;
        struct ListNode *p=NULL,*p2=NULL,*x=NULL;
        scanf("%d",&n);
        pHead1=(struct ListNode*)malloc(sizeof(struct ListNode));
        p=(struct ListNode*)malloc(sizeof(struct ListNode));
        pHead2=(struct ListNode*)malloc(sizeof(struct ListNode));
        p2=(struct ListNode*)malloc(sizeof(struct ListNode));
        pHead1->next=p;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&p->val);
            p->next=(struct ListNode*)malloc(sizeof(struct ListNode));
            x=p;
            p=p->next;
        }
        x->next=NULL;
        p=pHead1->next;
    
        pHead2->next=p2;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&p2->val);
            p2->next=(struct ListNode*)malloc(sizeof(struct ListNode));
            x=p2;
            p2=p2->next;
        }
        x->next=NULL;
        p2=pHead2->next;
    
        mergeHead=s.Merge(p,p2);
        while(mergeHead!=NULL)
        {
            printf("%d",mergeHead->val);
            mergeHead=mergeHead->next;
        }
        return 0;
    }
  • 相关阅读:
    飞入飞出效果
    【JSOI 2008】星球大战 Starwar
    POJ 1094 Sorting It All Out
    POJ 2728 Desert King
    【ZJOI 2008】树的统计 Count
    【SCOI 2009】生日快乐
    POJ 3580 SuperMemo
    POJ 1639 Picnic Planning
    POJ 2976 Dropping Tests
    SPOJ QTREE
  • 原文地址:https://www.cnblogs.com/dshn/p/8873178.html
Copyright © 2011-2022 走看看