-
-
未解决 [求助]单链表删除多个节点的问题。
-
发表于: 2020-11-21 20:36 1290
-
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <string.h>
#define LEN sizeof(struct student) // 结构的长度
struct student creat(); // 建立链表
void print(struct student head); // 打印链表
struct student del(struct student head,int num); // 删除一个节点
struct student
{
int num;
float score;
struct student next;
};
int n,temp; // 全局变量
void main()
{
struct student stu,p;
int m;
stu=creat();
p=stu;
print(stu);
do
{
printf("please enter the num to delete:");
scanf("%d",&m);
print(del(p,m));
}while(m);
system("pause");
}
struct student creat()
{
struct student p1,p2,head;
p1=p2=(struct student )malloc(LEN);
printf("please enter the num:");
scanf("%d",&p1->num);
printf("please enter the score:");
scanf("%f",&p1->score);
head=NULL;
n=0;
while(p1->num)
{
n++;
if(n==1) // 判断是否删除第一个节点
{
head = p1;
}
else
{
p2->next=p1;
}
p2=p1;
p1=(struct student *)malloc(LEN);
printf("please enter the num:");
scanf("%d",&p1->num);
printf("please enter the score:");
scanf("%f",&p1->score);
1 2 3 4 | } temp = n; p2 - > next = NULL; return head; |
};
void print(struct student head)
{
struct student p;
p=head;
printf("\nThere are %d records\n\n",n);
if(head)
{
do
{
printf("The num.%d score is %f\n",p->num,p->score);
p=p->next;
}
while(p);
}
}
struct student del(struct student head,int num)
{
struct student p1,p2;
if(head == NULL)
{
printf("An empty list\n");
goto end;
}
p1=head;
while(num != p1->num && p1->next != NULL)
{
p2=p1;
p1=p1->next;
}
if(p1->num == num)
{
if(p1==head)
{
head=p1->next;
}
else
{
p2->next=p1->next;
}
printf("Delete No.%d succeed\n",num);
n=n-1;
}
else
1 | printf( "%d not been found!\n" ,num); |
end:
return head;
};
为什么删除节点的时候,如果不删除第一个节点就没事,如果删除了第一个节点,后面输入什么,都会自动生成第一个节点。
第一个节点自动生成
不输入第一个节点,则无碍,请求大佬解答!万分感谢!
[培训]《安卓高级研修班(网课)》月薪三万计划,掌握调试、分析还原ollvm、vmp的方法,定制art虚拟机自动化脱壳的方法
赞赏
- [求助]单链表删除多个节点的问题。 1291