C语言实现顺序链表合并(此方法开辟新的节点空间来存储数据,原链表不被破坏,带头节点,两个原链表本身分别无重复元素)

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct node{
    int data;
    struct node *next;
};
struct node *create(){
    struct node *head;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;
    return head;
}
void Sq_insert(struct node *head,int num){/*顺序插入*/
    struct node *p,*q;
    p=head;
    while(p->next!=NULL&&p->next->data<num){
        p=p->next;
    }
    q=(struct node *)malloc(sizeof(struct node));
    q->data=num;
    q->next=p->next;
    p->next=q;
}
void show(struct node *head){/*打印链表*/
    struct node *p;
    p=head->next;
    while(p!=NULL){
        printf("%d\t",p->data);
        p=p->next;
    }
    printf("\n");
}
struct node *merge(struct node *head1,struct node *head2){/*链表合并后返回一个新链表*/
    struct node *p3,*q1,*q2,*q3,*head3;
    head3=create();
    p3=head3;
    q1=head1->next;
    q2=head2->next;
    while(q1&&q2){
            q3=(struct node *)malloc(sizeof(struct node));/*分配新的结点空间来存储复制过来的数据*/
            q3->next=NULL;
        if(q1->data<=q2->data){
            q3->data=q1->data;
            p3->next=q3;
            p3=q3;
            if(q1->data==q2->data){
                q2=q2->next;
            }
            q1=q1->next;
        }else{
            q3->data=q2->data;
            p3->next=q3;
            p3=q3;
            q2=q2->next;
        }
    }
    p3->next=q1?q1:q2;/*如果q1未空接q1,如果q1已空接q2*/
    return head3;
}
int main(){
    struct node *head1,*head2,*head3;
    head1=create();
    head2=create();
    srand(time(NULL));/*随机数种子*/
    for(int i=0;i<6;i++){
        Sq_insert(head1,rand());/*随机插入数据*/
        Sq_insert(head2,rand());
    }
    show(head1);
    show(head2);
    printf("\n\n");
    head3=merge(head1,head2);
    show(head3);/*合并后的链表为head3,打印head3即为合并后链表*/
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值