合并两个排序的链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
#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;
}
原文地址:https://www.cnblogs.com/dshn/p/8873178.html