新手问题。我有这个功能,释放前一个节点后添加节点时程序崩溃
void removeNodes(Node *start)
{
Node *temp;
int counter = 0;
while(start)
{
temp = start;
start = start->next;
free(temp);
counter++;
}
printf("%d node/s has been removed\n\n", counter);
}
在我的main()
,我有选择。
- 添加节点
- 删除所有节点
- 退出程序
有第一套环的没有问题,直到我决定免费,我只是选项创建的节点2.问题从这里开始。释放它们之后,我想添加另一组节点,在我再次进入第一个节点后程序崩溃。我做的第一件事是将我的main()
中的start
重置为NULL
。但它仍然打破了这个计划。
我正在阅读的这本书没有解释为什么会发生这种情况。或者,也许他们拥有它,但他们已经在最后一页。我在第340/632页=)..这里是新手。也许我只是失去了一些对其他老手来说非常简单的东西。请帮助我。 tnx ..
顺便说一下,这只是我的main()
函数的一个示例。我没有包括所有。
Node *start = NULL;
int choice;
int pos = 1;
int data;
int node_qty = 0;
while(1)
{
printf("1. Add node\n2. Delete all nodes\n3. Quit ");
scanf(" %d", &choice);
if(choice == 1)
{
if(!node_qty)
{
printf("Enter the value of the first node: ");
scanf(" %d", &data);
}
else
{
printf("Enter a value: ");
scanf(" %d", &data);
do
{
printf("Enter the position: ");
scanf(" %d", &pos);
if(pos > node_qty + 1)
{
printf("Invalid input. Current node quantity: %d\n", node_qty);
printf("\n\n\n\n\n\n\n\n\n");
system("PAUSE");
system("cls");
}
}while(pos < 1 || pos > node_qty + 1);
}
insertNode(&start, pos, data);
printf("\n\n\n\n\n\n\n\n\n");
system("PAUSE");
system("cls");
node_qty++;
}
else if(choice == 2)
{
removeNodes(start);
//reset
start = NULL;
node_qty = 0;
printf("\n\n\n\n\n\n\n\n\n");
system("PAUSE");
system("cls");
}
else if(choice == 3)
{
printf("Program ends");
break;
}
}
//then after all of that, I am making sure that it will free the nodes
removeNodes(start); //I don't think the problem is here.
这是我的加点功能
void insertNode(Node **start, int pos, int data)
{
Node *temp1 = malloc(sizeof(Node));
temp1->data = data;
Node *temp2 = *start;
if(pos == 1)
{
temp1->next = *start;
*start = temp1;
}
else
{
for(int i = 0; i < pos - 2; i++)
{
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
}
//and for checking, here's my print function
void printNode(Node *start)
{
while(start)
{
printf("%d ", start->data);
start = start->next;
}
printf("\n\n");
}
您需要发布剩余的代码。我怀疑你有一些问题填充列表。 –
也许问题在别处,它不是一个正确形成的链表。或者也许是别的。也许你应该显示处理选项的代码? – lurker
你应该发布一个完整的最小和可验证的例子。 –