单链表求集合

本文介绍了一种使用单链表实现链表操作的方法,包括创建链表、范围筛选和链表交集计算。通过输入不同的整数序列,演示了如何在两个链表中找出并打印它们的交集元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include<stdio.h>
#include<malloc.h>
typedef struct list
{
int num;
struct list *next;
}*LIST,listint;
LIST Creat(char n)
{
LIST head,p1,p2;
head=p1=(LIST)malloc(sizeof(listint));
printf("请输入%c单链表集合(以0未结束符):",n);
scanf("%d",&p1->num);
if(p1->num==0)
return head;
p1->next=NULL;
while(1)
{
p2=(LIST)malloc(sizeof(listint));
scanf("%d",&p2->num);
p2->next=NULL;
if(p2->num==0)
return head;
p1->next=p2;
p1=p2;
}
}
LIST range(LIST head)
{
LIST p1,p2,p3,p4;
p1=p2=p3=head;
char n=1;
p4=(LIST)malloc(sizeof(listint));
p4->next=NULL;
while(p1!=NULL)
{
while(p2!=NULL)
{
if(p2->next!=NULL&&p1->next!=NULL&&n==1)
{
p3=p2;
p2=p2->next;
}
n=1;
if(p1->num==p2->num)
{
p3->next=p2->next;
p2=p2->next;
n=0;
}
else if(p2->next==NULL)
p2=NULL;
}
p3=p2=p1=p1->next;
}
p1=head;
p2=p1->next;
while(p1->next!=NULL)
{
if(p1->num>p2->num)
{
p4->num=p1->num;
p1->num=p2->num;
p2->num=p4->num;
}
if(p2->next==NULL)
{
p1=p1->next;
p2=p1->next;
}
else if(p2->next!=NULL)
p2=p2->next;
}
return head;
}
LIST And(LIST h1,LIST h2)
{
int n=0;
LIST p1,p2,p3,p4,h3;
p1=h1;
p2=h2;
    h3=p3=(LIST)malloc(sizeof(listint));
p3->num=-1;
p3->next=NULL;
while(p1!=NULL&&p2!=NULL)
{
while(p1->num>p2->num)
{
if(p2->next!=NULL)
p2=p2->next;
else
return h3;
}
while(p1->num<p2->num)
{
if(p1->next!=NULL)
p1=p1->next;
else
return h3;
}
if(p1->num==p2->num)
{
n++;
if(n!=1)
{
p3->next=p4;
p3=p3->next;
p4->num=p1->num;
}
else
p3->num=p1->num;
p4=(LIST)malloc(sizeof(listint));
p4->next=NULL;
p2=p2->next;
}
}
return h3;
}
void print(LIST head)
{
LIST L;
L = head;
while(L!=NULL)
{
if(L->num!=-1)
{
printf("%d  ",L->num);
L = L->next;
}
else
{
printf("没有交集!\n");
L=NULL;
}
}
}
void main()
{
LIST h1,h2,h3;
while(1)
{
h1=Creat('A');
h2=Creat('B');
h1=range(h1);
h2=range(h2);
print(h1);
printf("\n");
print(h2);
h3=And(h1,h2);
printf("\n");
printf("得到交集为:\n");
print(h3);
printf("\n");
}
}


运行结果:

请输入A单链表集合(以0未结束符):5 4 3 2 1 0

请输入B单链表集合(以0未结束符):2 2 2 5 4 2 3 2 3 2 3 9 8 7 6 5 5 4 4 7 7 6 5 0

1 2 3 4 5

2 3 4 5 6 7 8 9

得到交集为:

2 3 4 5 

请输入A单链表集合:

作者:陈福林(fulinux)

20111227

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

fulinux

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

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

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

打赏作者

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

抵扣说明:

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

余额充值