|  | 
 
 
 楼主|
发表于 2021-1-31 16:21:29
|
显示全部楼层 
| #include <stdio.h> #include <malloc.h>
 
 typedef struct{
 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;
 struct list  *pre=NULL;
 struct list *u=NULL;
 
 int main()
 {
 int i=0,length;
 int n;
 printf("请输入链表的长度:\n");
 scanf("%d",&length);
 head = (struct list *)malloc(sizeof(struct list));
 L=head;
 printf("请依次输入链表的内容:\n");
 for(i=0;i<length;i++)
 {
 p = (struct list *)malloc(sizeof(struct  list));
 scanf("%d",&p->data);
 p->next=NULL;
 head->next=p;
 p->next=NULL;
 head=p;
 }
 int i1=0,length1;
 printf("请输入链表的长度:\n");
 scanf("%d",&length1);
 head1 = (struct list *)malloc(sizeof(struct list));
 L1=head1;
 printf("请依次输入链表的内容:\n");
 for(i1=0;i<length1;i1++)
 {
 p1=(struct list*)malloc(sizeof(struct list));
 scanf("%d",&p1->data);
 p1->next=NULL;
 head1->next=p1;
 p1->next=NULL;
 head1=p1;
 }
 //L和L1的差集的结果存储于La中,n是结果集合中元素个数,调用时为0
 p=L->next;
 p1=L1->next;
 pre=L;   //pre为L中p所指结点的前驱结点的指针
 while(p&&p1)
 {
 if(p->data<p1->data) //A链表中当前指针后移
 {
 
 n++;
 pre=p;
 p=p->next;
 
 }
 
 else if(p->data>p1->data)
 {
 p1=p1->next;  //B链表中当前结点指针后移
 }
 else
 {
 pre->next=p->next;
 u=p;
 free (u);
 }
 }
 
 return 0;
 }
 源码如上所示。已知两个链表A和B分别表示两个集合,其元素递增排列。求出A与B的交集,并存放在A链表中。
 | 
 |