两个有序链表的合并

题目描述:

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

解题思路:

具体思想就是新建一个链表,然后比较两个链表中的元素值,把较小的那个链到新链表中,由于两个输入链表的长度可能不同,所以最终会有一个链表先完成插入所有元素,则直接将另一个未完成的链表直接链入新链表的末尾。代码如下:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<string>
using namespace std;
struct node
{
    int x;
    struct node *next;
};
void merge(node *l1,node *l2)
{
    node *E=(struct node*)malloc(sizeof(struct node));
    node *H=(struct node*)malloc(sizeof(struct node));
    E=H;
    while(l1!=NULL&&l2!=NULL)
    {
        if(l1->x>l2->x)
        {
            E->next=l2;
            l2=l2->next;
        }
        else
        {
            E->next=l1;
            l1=l1->next;
        }
        E=E->next;
    }
    E->next=(l1!=NULL?l1:l2);//把剩下不为空的链表拼接上去
    while(H->next!=NULL)
    {
        H=H->next;
        cout<<H->x<<' ';   
    }
    cout<<endl;
}
int main()
{
    int n, m;
    node *H1, *E1,*H2,*E2;
    H1 = (struct node*)malloc(sizeof(struct node));
    E1 = (struct node*)malloc(sizeof(struct node));
    
    E1=H1;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> m;
        node *temp = (struct node*)malloc(sizeof(struct node));
        temp->x = m;
        temp->next = NULL;
        E1->next=temp;
        E1=temp;
    }
   
    H2=(struct node*)malloc(sizeof(struct node));
    E2=(struct node*)malloc(sizeof(struct node));
    E2=H2;
    for(int i=0;i<n;i++)
    {
        cin>>m;
        node *temp=(struct node*)malloc(sizeof(struct node));
        temp->x=m;
        temp->next=NULL;
        E2->next=temp;
        E2=temp;
    }
    merge(H1->next,H2->next);
    return 0;
}
原文地址:https://www.cnblogs.com/-citywall123/p/12447945.html