头歌:就地归并两个有序表

//有序表就地归并
#include<stdio.h>
#include<malloc.h> 
typedef  struct list {  
    int data;  
    struct list * next;  //下一个节点地址   
}list;  
//第一条链表 
struct list * L=NULL;//头
struct list * head=NULL;//首
struct list * p=NULL;  
//第二条链表
struct list * L1=NULL;//头
struct list * head1=NULL;//首
struct list * p1=NULL; 
//代理链表
struct list * L2=NULL;//头
struct list * q=NULL;//L2备用地址 
struct list * q1=NULL;//备用地址 
int main(){
    int i=0,length;
    printf("请输入链表的长度\n");
    scanf("%d",&length); 
    head=(struct list *)malloc(sizeof(struct  list)); 
    L=head;
    printf("请依次输入链表的内容\n");
    for(i;i<length;i++){
        p = (struct list *)malloc(sizeof(struct  list));
        scanf("%d",&p->data);
        p->next=NULL;
        head->next=p;
        head=p;
    }
    int i1=0,length1;
    printf("请输入链表的长度\n");
    scanf("%d",&length1);
     
    head1=(struct list *)malloc(sizeof(struct  list)); 
    L1=head1;
    printf("请依次输入链表的内容\n");
    for(i1;i1<length1;i1++){
        p1= (struct list *)malloc(sizeof(struct  list));
        scanf("%d",&p1->data);
        p1->next=NULL;
        head1->next=p1;
        head1=p1;
    }
    L2=(struct list *)malloc(sizeof(struct  list));
    q=L2;//备用合并链表起始地址 
    p=L->next;
    p1=L1->next;
    while(p&&p1){   
      if(p->data<p1->data){
        L2->next=p;
        L2=p;
        p=p->next;
    }else if(p->data==p1->data){
        L2->next=p;
        L2=p;
        p=p->next;
        q1=p1->next;//备用相同元素的下一个地址指向 
        free(p1);
        p1=q1;
        
    }else if(p->data>p1->data){
        L2->next=p1;
        L2=p1;
        p1=p1->next;
    }       
    }
   L2->next=p?p:p1;
   free(L1);
   printf("合并后链表的内容\n");
    p=q->next;
    while(p){
    printf("%d ",p->data);
    p=p->next;
    }
    
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Code攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值