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;
    }
  • 相关阅读:
    如何在SQL Server 2005 中为安装程序增加计数器注册表项值
    C++ 基础小知识学习[1]
    同时支持火狐和IE的输入框内容改变事件
    3D圆角
    Jquery选择器测试
    asp.net 中的 MD5加密和DES加解密算法类
    简单页面控件赋值
    继承IHttpHandler接口实现给网站图片添加水印
    asp.net Ajax
    JQuery操作iframe父页面与子页面的元素与方法
  • 原文地址:https://www.cnblogs.com/dshn/p/8873178.html
Copyright © 2011-2022 走看看