将两个从小到大排列的链表合并为一个新链表(仍然有序排列),若遇到相同的元素,则在合并时去掉重复元素。输出合并前的两个链表,输出合并后的链表,检查合并是否成功。(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;
    int count=0;
    while(p){
        printf("%d\t",p->Data);
        count++;
        if(count%10==0){
            printf("\n");
        }
        p=p->next;
    }
    printf("\n");
}
void merge(struct Node *head1,struct Node *head2){/*合并后链表头指针为head1*/
    struct Node *p1,*q1,*q2;
    p1=head1;
    q1=head1->next;
    q2=head2->next;
    while(q1&&q2){
        if(p1!=head1&&p1->Data==q1->Data){
            q1=q1->next;
        }else if(p1!=head1&&p1->Data==q2->Data){
            q2=q2->next;
        }else 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;
            q2=q2->next;
        }
    }
    if(q1==NULL){
        while(q2){
            if(p1!=head1&&p1->Data==q2->Data){
                q2=q2->next;
            }else{
                p1->next=q2;
                p1=q2;
                q2=q2->next;
            }
        }
    }else{
        while(q1){
            if(p1!=head1&&p1->Data==q1->Data){
                p1=p1->next;
            }else{
                p1->next=q1;
                p1=q1;
                q1=q1->next;
            }
        }
    }
    p1->next=NULL;
}
int main(){
    struct Node *head1,*head2;
    head1=create();
    head2=create();
    for(int i=0;i<20;i++){
        Sq_insert(head1,rand()%15);
        Sq_insert(head2,rand()%15);
    }
    printf("链表一:\n");
    show(head1);
    printf("链表二:\n");
    show(head2);
    merge(head1,head2);
    printf("合并后链表:\n");
    show(head1);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值