【发布时间】:2018-10-12 18:00:14
【问题描述】:
我在删除双向链表中的节点时遇到问题,程序崩溃,我无法找出问题所在。你能帮我么? 这是创建新节点、查看它们并删除它们的完整代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Test
{
int id;
};
typedef struct Node {
struct Test structure;
struct Node * next;
struct Node *prev;
}TNode;
typedef TNode* Node;
void NewNode(struct Test p, Node *pp)
{
Node temp;
temp = (Node)malloc(sizeof(struct Node));
temp->structure = p;
temp->next = *pp;
temp->prev = NULL;
if(*pp != NULL)
{
(*pp)->prev = temp;
}
*pp = temp;
}
void ReadStructure(struct Test * p)
{
printf("\nID:");
scanf(" %d", &p->id);
}
void ViewList(Node node)
{
Node temp;
while(node != NULL)
{
temp = node->prev;
if(node->prev == NULL)
{
printf("Prev = NULL\n");
}
else
{
printf("Prev: %d\n", temp->structure.id);
}
printf("Curr: %d\n", node->structure.id);
node = node->next;
}
}
void Delete(Node * head, Node del)
{
if(*head == NULL || del == NULL)
{
return;
}
if(*head == del)
{
*head = del->next;
}
if(del->next != NULL)
{
del->next->prev = del->prev;
}
if(del->prev != NULL)
{
del->prev->next = del->next;
}
free(del);
return;
}
int Menu()
{
int c;
printf("*** M E N U ***\n"
"1 - New Node\n"
"2 - View List\n"
"3 - Delete\n"
"0 - Exit\n"
"\n>> ");
scanf(" %d", &c);
return c;
}
int main()
{
int c;
struct Test test;
Node list = NULL;
Node del = NULL;
do {
c = Menu();
switch (c)
{
case 1: ReadStructure(&test);
NewNode(test, &list); break;
case 2: ViewList(list); break;
case 3: printf("\nElement to Delete: ");
scanf("%d", &del->structure.id);
Delete(&list, del); break;
default: c = 0;
}
} while (c != 0);
return 0;
}
我认为问题与 Node del 的 scanf() 有关,但我不确定。当我只是将list 或list->next 作为函数Delete() 的第二个参数传递时,它可以工作。代码一切正常吗?
【问题讨论】:
-
用gdb运行程序,得到回溯。确保使用调试进行编译(gcc 上的
-g)。这会告诉你它崩溃的确切位置。 -
我做了调试,当我输入要删除的元素并回车时,我得到了分段错误
-
我不知道它在哪里崩溃,我只是在 gdb 中输入了 run
-
它是
run,然后在崩溃时输入bt。最上面一行显示了它崩溃的位置。
标签: c doubly-linked-list