2.对链表的删除操作
代码部分:
#include<stdio.h>
#include<malloc.h>
#define NULL 0
#define LEN sizeof(struct student)
struct student *creat(void);
struct student{
long num;
float score;
struct student *next;
};
struct student *creat(void){ //上一章已经介绍过,动态链表的生成
int n=0;
struct student *head,*p1,*p2;
p1=p2=(struct student *)malloc(LEN); //有个 * 号是强制转换。用malloc函数开辟第一个节点。
scanf("%d,%f",&p1->num,&p1->score); //向 p1 指针指向的地址添加数据
head=NULL; // 先让头指针为空
while(p1->num!=0) //约定学号不为0
{
n=n+1;
if(n==1)
head=p1; //将 p1 指针 指向的地址赋给 head
else
p2->next=p1; //p2->next 指向了新开辟的 p1 指向的新开辟的数据结构
p2=p1; //将 p1 所指向的地址赋给 p2
p1=(struct student *)malloc(LEN); // p1 再重新指向一个新开辟的地址
scanf("%d,%f",&p1->num,&p1->score); //向 p1 指向的这个地址输入数据, 也就是向新开辟的地址输入数据
}
p2->next=NULL; //最后赋予NULL;
return(head);
}
struct student *del(struct student *head,long num) //本次重点,链表的删除
{
struct student *p1,*p2;
if(head==NULL) { printf(" nlist null! \n"); return head; }
p1=head; // 将head所指向的地址赋给 p1
while(num!=p1->num && p1->num!=NULL)
{
p2=p1; //将 p1 所指向的 地址赋给p2 ,让p2也指向这个地址。
p1=p1->next; //p1 继续寻找下一个数据(节点)
}
if(num==p1->num) // 找到这个节点了
{
if(p1==head)
head=p1->next; //若head(p1指向首节点)指向的节点就是要删除的节点,就把第二个节点赋给head
else
p2->next=p1->next; //将下个节点的地址赋给前一个节点的地址
printf("delete:%d \n",num);
// n=n-1;
}
else
printf("%d can not found!\n ",num);
return head;
}
void main(){
struct student *head,*p;
head=creat();
head=del(head,10); //会重新返回一个head指针
p=head;
if(head!=NULL)
while(p!=NULL)
{
printf("%d %f ",p->num,p->score);
p=p->next;
printf("\n");
}
}