有两个链表a和b,设结点中包含学号和姓名,从a链表中删除和b链表中相同学号的结点

来源:互联网 发布:找出出现最多的词 算法 编辑:程序博客网 时间:2024/05/23 12:53
#include <stdio.h>#include <stdlib.h>#define LEN sizeof(struct student)#define NULL 0int n=0;struct student {int num;char name[20];struct student *next;};struct student *creat(void)  //创建学生结构体链表{    struct student *head,*p1,*p2;    p1=p2=(struct student *)malloc(LEN);    scanf("%d %s",&p1->num,p1->name);    head=NULL;    while(p1->num!=0){            n++;       if(n==1) head=p1;        else p2->next=p1;        p2=p1;        p1=(struct student *)malloc(LEN);        scanf("%d %s",&p1->num,p1->name);        }    p2->next=0;    n=0;    return head;}struct student *deletesame(struct student *a,struct student *b){       //删除从a中删除b中相同学号的学员struct student *head=a,*p1=a,*p2=b,*p3=a;    int k=0,s=0;    while(p1!=0){        while(p2!=0){            if(p1->num==p2->num)            {                if(k==0) {head=p1->next;                                //如果a链表头发现相同需要删除。                    s++;                    }                    else {                            p3->next=p1->next;                            s++;                        }            }            p2=p2->next;                  }        if(s>0){                                      //发生删除操作后的处理            s=0;            p2=b;            p1=p1->next;        }else{                                          // 未发生删除操作后的处理            p2=b;            k++;            p3=p1;            p1=p1->next;}}return head;}void print( struct student *p){    while(p!=0)      { printf("%d %s\n",p->num,p->name);        p=p->next;}}int main(){   struct student *a=creat();    struct student *b=creat();    struct student *head=deletesame(a,b);    print(head);    return 0;}

阅读全文
0 0
原创粉丝点击