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");
}
void merge(struct node *head1,struct node *head2){/*以head1作为合并后的链表的头节点*/
    struct node *p1,*q1,*q2,*temp;
    p1=head1;
    q1=head1->next;
    q2=head2->next;
    while(q1&&q2){
        if(q1->data<q2->data){
            p1->next=q1;
            p1=q1;
            q1=q1->next;
        }else if(q1->data>q2->data){
            p1->next=q2;
            p1=q2;
            q2=q2->next;
        }else{
            p1->next=q1;
            p1=q1;
            q1=q1->next;
            temp=q2;
            q2=q2->next;
            free(temp);
        }
    }
    p1->next=q1?q1:q2;/*如果q1未空接q1,如果q1已空接q2*/
}
int main(){
    struct node *head1,*head2;
    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");
    merge(head1,head2);
    show(head1);/*合并后链表合到了head1,打印head1即为合并后链表*/
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值