链表合并

1.建立三个链表

2.定义三个链表指针*t*p*q

3.*p*q分别指向两个链表的next结点;*t指向一个链表的头结点,这个头结点就成为新链表的头结点

4.选择下一个结点,根据一定的判定条件,如果下一个结点为p的结点,(1)先让t指向p(2)t向后移动既t=t->next(3)p的指向后移既p=p->next

5.判断是否有一个链表合并完,如果q,p有一个为空即为有一个链表合并完,这样只需处理另一个结点全部连接到新链表中即可。如果p为空,执行t->next=q;break;

注:一定不能忽略break

6.返回新链表的头结点.

#include <iostream>
#include<stdlib.h>
using namespace std;
struct node
{
    int x;
    struct node *next;
};
//顺序建表
struct node *creatListShun(int lenth)
{
    struct node *head,*t,*p;
    int i;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;
    t=head;
    for(i=0; i<lenth; i++)
    {
        p=(struct node *)malloc(sizeof(struct node));
        p->x=i;
        p->next=NULL;
        t->next=p;
        t=p;
    }
    return head;
}
//链表合并
struct node  *hebing(struct node *head1,struct node *head2)
{
    struct node *t,*p,*q;
    t=head1;
    p=head1->next;
    q=head2->next;
    while(t)
    {
        if(p->x<q->x)
        {
            t->next=p;
            p=p->next;
            t=t->next;
        }
        else
        {
            t->next=q;
            q=q->next;
            t=t->next;
        }
        if(p==NULL)
        {
            t->next=q;
            break;
        }
        if(q==NULL)
        {
            t->next=p;
            break;
        }
    }
    return head1;
}
int main()
{
    struct node *head1,*t1;
    head1=creatListShun(10);//顺序建链表
    t1=head1->next;
    cout<<"顺序建链表1 :";
    while(t1!=NULL)
    {
        cout<<t1->x<<" ";
        t1=t1->next;
    }
cout<<endl;

    struct node *head2,*t2;//逆序建链表
    head2=creatListShun(10);
    t2=head2->next;
    cout<<"顺序建链表2 :";
    while(t2!=NULL)
    {
        cout<<t2->x<<" ";
        t2=t2->next;
    }
    cout<<endl;
    //链表合并
    head1=hebing(head1,head2);
    t1=head1->next;
    cout<<"链表合并 :";
    while(t1!=NULL)
    {
        cout<<t1->x<<" ";
        t1=t1->next;
    }
    cout<<endl;
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值