/*有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点*/
#include <stdio.h>
#include <stdlib.h>
typedef struct student{
long num;
char name[10];
struct student *next;
}student,*Student;
//创建链表
Student creat()
{
Student s;
int n = 0;
Student p1,p2;
s = p1 = p2 = (Student) malloc(sizeof(student));
printf("请输入学生学号和姓名:\n");
scanf("%ld %s",&p1->num,&p1->name);
while(p1->num != 0)
{
n = n + 1;
if(n == 1) s = p1;
else p2->next = p1;
p2 = p1;
p1 = (Student) malloc(sizeof(student));
scanf("%ld %s",&p1->num,&p1->name);
}
p2->next = NULL;
return s;
}
//输出链表
void print(Student s)
{
Student p;
printf("\nNow,The records are:\n");
p = s->next;
if(s != NULL)
{
do
{
printf("%ld %s\n",p->num,p->name);
p = p->next;
}while(p != NULL);
}
}
void delect(Student a,Student b)
{
Student p1,p2,q1,q2;
int flag = 0;
p1 = a;
q1 = b->next;
while(q1)
{
p1 = a;
while(p1->next != NULL)
{
flag = 0;
p2 = p1->next;
if(p2->num == q1->num)
{
p1->next = p2->next;
flag = 1;
}
if(flag == 0)
p1 = p1->next;
}
q1 = q1->next;
}
}
int main()
{
Student a;
Student b;
a = (Student)malloc(sizeof(student));
b = (Student)malloc(sizeof(student));
a->next = creat();
b->next = creat();
print(a);
print(b);
delect(a,b);
print(a);
}
谭浩强C程序设计(第四版)p330第11题
为了方便删除,建立带头结点的链表,每次循环都是从a链表的头部寻找与b链表学号相同的结点,然后删除,直到b链表结束。