题目:
已知两个元素按照值递增有序排列的线性表A和B,且同一表中元素值各不相同。试构造一个线性表C,其元素为A和B中元素的交集,且元素按照值递增有序排列。(采用单向链表的存储方式)
下面是我写的程序:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
node *input()
{
int i;
node *p,*q,*r;
q=(node *)malloc(sizeof(node));
q->next=NULL;
p=q;
printf("请输入不重复的数据(递增,以0结尾):\n");
scanf("%d",&i);
while(i!=0)
{
r=(node *)malloc(sizeof(node));
r->data=i;
r->next=NULL;
p->next=r;
p=r;
scanf("%d",&i);
}
return(q);
}
void output(node *head)
{
node *p;
p=head;
while(p)
{
printf("%d\n",p->data);
p=p->next;
}
}
void fun(node *ahead,node *bhead,node *chead)
{
node *p,*q,*r;
p=ahead->next;
q=bhead->next;
r=chead->next;
while(p!=NULL&&q!=NULL)
{
if(p->data<q->data) p=p->next;
else {if(p->data==q->data) {r->data=p->data;p=p->next;q=q->next;r=r->next;}
else q=q->next;}}
}
main()
{
node *ahead,*bhead,*chead;
printf("线性表A\n");
ahead=input();
printf("线性表B\n");
bhead=input();
fun(ahead,bhead,chead);
printf("取交集后的数据:\n");
output(chead);
}
调试时一执行到fun函数,就错误了。。。
求大神帮帮忙呀!!!感激不尽。。。
修改后的程序如下(修改地方已用符号标出):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
node *input()
{
int i;
node *p,*q,*r;
q=(node *)malloc(sizeof(node));
q->next=NULL;
p=q;
printf("请输入不重复的数据(递增,以0结尾):\n");
scanf("%d",&i);
while(i!=0)
{
r=(node *)malloc(sizeof(node));
r->data=i;
r->next=NULL;
p->next=r;
p=r;
scanf("%d",&i);
}
return(q);
}
void output(node *head)
{
node *p;
p=head->next;
while(p)
{
printf("%d\n",p->data);
p=p->next;
}
}
void fun(node *ahead,node *bhead,node * &chead) //chead对其引用
{
node *p,*q,*r,*tmp;
p=ahead->next;
q=bhead->next;
chead=(node*)malloc(sizeof(node));
chead->next=NULL;
r=chead;
while(p!=NULL&&q!=NULL)
{
if(p->data<q->data) p=p->next;
else
{
if(p->data==q->data)
{
tmp=(node*)malloc(sizeof(node));
tmp->data=p->data;
tmp->next=NULL;
p=p->next;
q=q->next;
r->next=tmp;
r=r->next;
}
else q=q->next;
}
}
}
int main()
{
node *ahead,*bhead,*chead;
printf("线性表A\n");
ahead=input();
printf("线性表B\n");
bhead=input();
fun(ahead,bhead,chead);
printf("取交集后的数据:\n");
output(chead);
return 0;
}
本回答被提问者和网友采纳