C语言复习6

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;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值