我在双向链表中遇到错误(碎片错误) [英] Im getting an error (fragmentation fault) in my doubly linked list
本文介绍了我在双向链表中遇到错误(碎片错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
void DeleteNode()
{
struct node *current;
struct node *prev;
int found = 0;
int n;
prev = allocate();
current = allocate();
current = head;
prev = NULL;
printf("\nEnter the value to eliminate: ");
scanf("%d",&n);
if(head != NULL)
{
//Assume list: 45,56,22,65
//We want to delete 22
while(current != NULL && found != 1)
{
if(current -> data == n)
{
if(current == head)
{
head = head -> next;
head -> previous = NULL;
}
else if(current == tail)
{
prev -> next = NULL;
tail = prev;
}
else
{
prev -> next = current -> next; //
current -> next -> previous = prev; //
}
printf("\n %d was succesfully deleted from the list.\n",n);
found = 1;
}
prev = current; //45,56,22
current = current -> next; //56,22,65
}
if(found == 0)
printf("\n%d is not found in the list!\n",n);
else
{
free(prev);
}
}
else
printf("\nThe list is empty\n");
}
我的尝试:
这是我的代码,我试图从列表中删除一个数字。这是一个双重链表。问题是当我在列表中只有1个数字并且我尝试删除它时,我得到分段错误。其余的工作正常。* /
What I have tried:
This is my code, I am trying to delete a number from the list. This is a doubly linked list. The problem is when I have only 1 number in the list and i try to delete it, i get segmentation fault. For the rest it works.*/
推荐答案
if(current == head)
{
head = head -> next;
head -> previous = NULL;
}
如果这是列表中唯一的项目,那么 head - > next
将是 NULL
。所以第二行会导致分段错误。
If this is the only item in the list then head -> next
will be NULL
. So the second line will cause the segmentation fault.
这篇关于我在双向链表中遇到错误(碎片错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文