【发布时间】:2018-08-08 02:55:29
【问题描述】:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct student
{
int ID;
int age;
struct student *next;
};
struct student *head = 0;
struct student *first = 0;
struct student *temp = 0;
void create_list()
{
static int counter = 1;
head = (struct student *)malloc(sizeof(struct student));
printf("Enter the student no. %d ID\n",counter);
scanf_s("%d", &head->ID);
printf("Enter the student no. %d age\n", counter);
scanf_s("%d", &head->age);
if (first != 0)
{
temp->next = head;
temp = head;
}
else
{
first = temp = head;
}
counter++;
}
void read_list()
{
temp->next = 0;
temp = first;
int counter = 1;
first = 0;
while (temp != 0)
{
printf("------------------Node number : %d---------------\n", counter);
printf("The Student id is : %d\n", temp->ID);
printf("The Student age is : %d\n", temp->age);
counter++;
temp = temp->next;
}
printf("NULL\n");
printf("-------------No. of nodes in the list = %d\n------------------", counter);
}
void delete_list(struct student **head, int position)
{
if (*head == NULL)
return;
struct student* temp = *head;
if (position == 0)
{
*head = temp->next;
temp = 0;
return;
}
for (int i = 0; temp != NULL && i<position - 1; i++)
temp = temp->next;
if (temp == NULL || temp->next == NULL)
return;
struct student *next = temp->next->next;
temp->next=0;
temp->next = next;
}
void main()
{
int choice = 0;
while (choice != 99)
{
printf("Please enter a choice from the list:\n");
printf("1- Create Node\n");
printf("2- Read List\n");
printf("3- Delete Node\n");
printf("99- Exit\n");
scanf_s("%d", &choice);
switch (choice)
{
case 1:
create_list();
break;
case 2:
read_list();
break;
case 3:
delete_list(&head,2);
break;
}
}
}
我的删除功能遇到了很多问题。我正在创建一个链接节点列表。我创建了读取和创建函数,但是每当我尝试删除一个节点并移回所有节点时,它都会给我一个错误。我可以就问题所在寻求帮助吗?
错误是每当我再次打印列表时,它就会停止并且不打印任何内容。
【问题讨论】:
-
错误是什么?请提供minimal reproducible example。
-
请注意,
<stdlib.h>声明了malloc()等,因此不需要非标准的<malloc.h>,除非您使用它的一些额外功能,而您没有使用。你没有概述你输入的值——或者你得到的错误输出。这是 MCVE (minimal reproducible example) 的重要组成部分。我们不应该猜测。调试时,您可以在每次操作后调用read_list()函数。 -
你的全局变量
temp令人担忧;我不清楚它是如何使用的。对您来说似乎很重要,因为您在删除代码中仔细设置了它,但为什么呢?同样,全局变量next可能不应该是全局变量。使用全局变量head是允许的——它通常不是最好的选择,但没关系。这意味着您一次只能使用此代码管理一个列表,但是当您刚开始时,这没关系。在类 Unix 系统上使用void main()无效;正确的返回类型是int。 Windows 文档void main()所以它不会自动出错。 -
你为什么用
delete_list(&head,2);固定2?delete_list的预期行为是什么?只是删除最后一个节点? -
@F.Igor 我将其设置为示例,因此如果我输入 5 个节点作为示例并删除了第 2 个节点,它会将它们向后移动 1 个步骤,并且会在没有第 2 个节点的情况下再次打印 4 个节点
标签: c linked-list