回复 4楼 迷途流浪
求两个链表的差
#include"stdio.h"
#include"malloc.h"
#include"stdlib.h"
#define SIZE sizeof(snode)
typedef struct student
{
int num;
struct student *next;
}snode;
snode *create1();
snode *create2();
//创建链表
void print(snode *head);
//打印链表
snode *diffence(snode *A,snode *B);
void main(void)
{
snode *head2,*head1,*head3;
head1=create1();
head2=create2();
printf("\n链表1为:\n");
print(head1);
printf("\n链表2为:\n");
print(head2);
printf("\n");
printf("两链表的差为:\n");
head3=diffence(head1,head2);
print(head3);
printf("\n");
}
snode *create1()
{
snode *head,*p,*q;
p=q=(snode *)malloc(sizeof(SIZE));
head=(snode *)malloc(sizeof(SIZE));
int n=0,num1;
FILE *fp;
fp=fopen("D:\\qq.txt","r");
fscanf(fp,"%d",&num1);
p->num=num1;
while(!feof(fp))
//
{
n++;
if(n==1)
head->next=p;
//建立带头节点的链表
else
q->next=p;
q=p;
p=(snode *)malloc(sizeof(SIZE));
fscanf(fp,"%d",&num1);
p->num=num1;
}
q->next=NULL;
return (head);
}
snode *create2()
{
snode *head,*p,*q;
p=q=(snode *)malloc(sizeof(SIZE));
head=(snode *)malloc(sizeof(SIZE));
int n=0,num1;
FILE *fp;
fp=fopen("D:\\aa.txt","r");
fscanf(fp,"%d",&num1);
p->num=num1;
while(!feof(fp))
//这
{
n++;
if(n==1)
head->next=p;
//建立带头节点的链表
else
q->next=p;
q=p;
p=(snode *)malloc(sizeof(SIZE));
fscanf(fp,"%d",&num1);
p->num=num1;
}
q->next=NULL;
return (head);
}
void print(snode *head)
{
snode *p;
p=head->next;
//带头结点
while(p!=NULL)
{
printf("%6d",p->num);
p=p->next;
}
}
snode *diffence(snode *A,snode *B)
{
snode *pa=A->next,*pb,*s,*r,*c;
c=(snode *)malloc(sizeof(SIZE));
c->next=NULL;
r=c;
while(pa!=NULL)
{
pb=B->next;
while(pb->num!=pa->num && pb!=NULL)
{
pb=pb->next;
}
if(pb=NULL)
{
s=(snode *)malloc(sizeof(SIZE));
s->num=pa->num;s->next=NULL;
r->next=s;
r=s;
}
pa=pa->next;
}
return(c);
}
[
本帖最后由 zd123 于 2009-9-6 21:29 编辑 ]