A链表删去与B链表相同的元素
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN sizeof(struct Student)
struct Student{
int ID;
char Name[100];
struct Student*Next;
};
struct Student*Creat(void){
struct Student*p1,*p2,*head;
int Student_Num=0;
head=NULL;
p1=(struct Student*)malloc(LEN);
scanf("%d %s",&p1->ID,p1->Name);
while(p1->ID>0){
Student_Num++;
if(Student_Num==1) head=p1;
else p2->Next=p1;
p2=p1;
p1=(struct Student*)malloc(LEN);
scanf("%d %s",&p1->ID,p1->Name);
}
if(head!=NULL) p2->Next=NULL;//容易忽略
return (head);
}
struct Student*Delete(struct Student*headA,struct Student*headB){
struct Student*p1,*p2,*p3;
p1=p2=headA;
p3=headB;
do{
if(p1->ID==p3->ID&&strcmp(p1->Name,p3->Name)==0){
//如果头结点要删掉
if(p1==headA){
if(p1->Next!=NULL) headA=p1->Next;
//只有一个头结点
else headA=NULL;
}
//如果是后面的结点要删掉
else{
if(p1->Next!=NULL) p1=p2->Next=p1->Next;
//如果要删的是最后一个
else p2->Next=NULL;
}
}
p3=p3->Next;
//把A链表的其中一个跟B链表的全部比较完了
if(p3==NULL){
p3=headB;
if(p1->Next!=NULL) p1=p1->Next;
else p1=NULL;
}
}while(p1!=NULL);
return (headA);
}
void Print(struct Student*head){
struct Student*Temp;
Temp=head;
if(head!=NULL){
do{
printf("%d %s\n",Temp->ID,Temp->Name);
Temp=Temp->Next;
}while(Temp!=NULL);
}
else printf("空链表!\n");
}
int main(){
struct Student*headA,*headB;
printf("如果学生的序号输入小于等于0的数,停止链表长度增加!\n");
printf("\n链表A:\n");
headA=Creat();
Print(headA);
if(headA!=NULL){
printf("\n链表B:\n");
headB=Creat();
Print(headB);
headA=Delete(headA,headB);
printf("\n此时的链表A:\n");
Print(headA);
free(headB);
}
else{
printf("\n故意找茬是不是?\n");
}
free(headA);
return 0;
}