[此贴子已经被作者于2017-3-23 09:41编辑过]


程序代码:#include <stdio.h>
#include <malloc.h>
#define N 9
typedef struct data
{
int value;
struct data* next;
}tdata,*pdata;
void prnlist(pdata head)
{
pdata pfirst=head->next;
while(pfirst!=NULL)
{
printf("%d ",pfirst->value);
pfirst=pfirst->next;
}
printf("\n");
}
int main(int argc, char* argv[])
{
pdata head1,pfirst1,psecond1;
pfirst1=(pdata)malloc(sizeof(tdata));//第一个链表哑节点
head1=pfirst1;
head1->value=0;
head1->next=NULL;
psecond1=pfirst1;
int i;
printf("请录入第一组数据 :\n");
for(i=0;i<N;i++)
{
pfirst1=(pdata)malloc(sizeof(tdata));
scanf("%d",&pfirst1->value);
pfirst1->next=NULL;
psecond1->next=pfirst1;
psecond1=pfirst1;//我弄错了,Psecond1指向pfirst1是为了更新指针,让其前移。
}
printf("请录入第二组数据:\n");
pdata pfirst2=(pdata)malloc(sizeof(tdata));//第二个链表哑节点
pdata head2=pfirst2;
head2->value=0;
head2->next=NULL;
pdata psecond2=pfirst2;
for(i=0;i<N;i++)
{
pfirst2=(pdata)malloc(sizeof(tdata));
scanf("%d",&pfirst2->value);
pfirst2->next=NULL;
psecond2->next=pfirst2;
psecond2=pfirst2;//我弄错了,Psecond1指向pfirst1是为了更新指针,让其前移。
}
printf("你所录入的两组数据如下:\n");
prnlist(head1);
prnlist(head2);
printf("共有数据如下:\n");
for(pfirst1=head1->next;pfirst1!=NULL;pfirst1=pfirst1->next)//遍历链表1
{
for(pfirst2=head2->next;pfirst2!=NULL;pfirst2=pfirst2->next)//遍历链表2
{
if(pfirst2->value==pfirst1->value) printf("%d ",pfirst2->value);//如果链表2中有链表1的值,则打印该值。
}
}
printf("\n");
free(head1);//释放错了,你只释放了哑节点的空间,但没有释放之后节点的空间。
free(head2);//要释放链表的空间,需要遍历链表,一个指针不断前移,然后一边释放,这里会需要一个指针指向下一个节点。否则将无法遍历链表
return 0;
}
[此贴子已经被作者于2017-3-23 22:14编辑过]
