有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同 学号的那些结点。
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct stu{ char num[6];char name[10]; struct stu *next; }List; int main(int argc, char *argv[]) { List a[6]={{"101","wang"},{"103","li"},{"105","chang"},{"106","wei"},{"101","zhang"},{"107","zhao"}}; List b[3]={{"101","chang"},{"103","mao"},{"105","zhang"}}; int i,j; List *p,*p1,*p2,*pt,*head1,*head2; head1=a;head2=b; for(p1=head1,i=1;p1<a+6;i++) { p=p1; p1->next=a+i; printf("%8s%8s\n",p->num,p->name); p1=p1->next; } p->next=NULL;printf("\n"); for(p2=head2,i=1;p2<b+3;i++) { p=p2; p2->next=b+i; printf("%8s%8s\n",p->num,p->name); p2=p2->next; } p->next=NULL;printf("\n"); p1=pt=head1; while(p1!=NULL) { p2=head2; while(p2!=NULL&&strcmp(p1->num,p2->num)!=0) p2=p2->next; if(p2!=NULL&& strcmp(p1->num,p2->num)==0) if(p1==head1)head1=p1->next; else pt->next=p1->next; else pt=p1; p1=p1->next; } p1=head1; printf("\n\n"); while(p1!=NULL) { printf("%8s%8s\n",p1->num,p1->name); p1=p1->next; } return 0; }
/* //方法二 p2=head2; while(p2!=NULL) { p1=pt=head1; while(p1!=NULL) { if(strcmp(p1->num,p2->num)==0)//如果学号相等,则删除该p1节点 ,p1往后移 { if(p1==head1) { head1=p1->next;pt=p1->next; } else pt->next=p1->next; } else//否则pt记录其前置节点 ,p1往后移 pt=p1; p1=p1->next; } p2=p2->next; } */