关于删除动态链表的问题,在VS2018上面运行的
#include<stdio.h>#include<stdlib.h>
#include<malloc.h>
struct student
{
int num;
float score;
struct student* next;
};
#define LEN sizeof(struct student)
struct student* creat();
struct student* delete(struct student *head,int num);
void print();
int n;
void main()
{
struct student* stu, * p;
int n;
stu = creat();
p = stu;
print(p);
#if 1
printf("Please enter the num to delete:");
scanf_s("%d", &n);
print(delete(p, n));
#endif
printf("\n\n");
system("pause");
}
struct student* creat()
{
struct student* head;
struct student* p1, * p2;
p1 = p2 = (struct student*)malloc(LEN);
printf("Please enter the num :");
scanf_s("%d", &p1->num);
printf("Please enter the score :");
scanf_s("%f", &p1->score);
n = 0;
head = NULL;
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_s("%d", &p1->num);
if (p1->num != 0)
{
printf("Please enter the score :");
scanf_s("%f", &p1->score);
}
}
p2->next = NULL;
return head;
}
#if 1
struct student* delete(struct student* head, int num)
{
struct student* q1, * q2;
if (head == NULL)
{
printf("\nThis list is NULL!\n");
goto END;
}
q1 = head;
while (q1->num != 0 && q1->next != NULL)
{
q2 = q1;
q1 = q1->next;
}
if (q1->num == num)
{
if (q1 == head)
{
head = q1->next;
}
else
{
q2->next = q1->next;
}
printf("\nDelete NO:%d succeed!\n", num);
n = n - 1;
}
else
{
printf("%d not been found!\n",num);
}
END:
return head;
}
#endif
void print(struct student* head)
{
struct student* p;
printf("There are %d record\n", n);
p = head;
if (head)
{
do
{
printf("学号%.2d学生成绩为%2.1f\n", p->num, p->score);
p = p->next;
} while (p);
}
}
会报“CL.exe"已退出,代码为2 https://zhidao.baidu.com/question/459190313.html
页:
[1]