我正在尝试编写代码,从双链表中删除给定位置的元素。但是,我的代码导致该元素没有被删除,而是被垃圾数据替换。
我测试了列表4,5,11,12,6,9
上的代码并尝试删除第三个元素(11)。结果是4,5,767133(trash),12,6,9
.
谁能告诉我下面的代码有什么问题吗?
struct L2k{
unsigned int count;
struct el_L2k *head;
struct el_L2k *tail;
};
struct L2k* removeFromPosition(struct L2k *L2k,int position)
{
if(position > L2k->count || position < 1)
{
printf("No such position\n");
return L2k;
}
int i;
struct el_L2k *temp = L2k->head;
for(i=1;i<position;i++)
temp=temp->next;
printf("Deleting %d",temp->data);
if(temp->prev!=NULL)
temp->prev->next=temp->next;
else
L2k->head=temp->next;
if(temp->next!=NULL)
temp->next->prev=temp->prev;
else
L2k->tail=temp->prev;
L2k->count--;
free(temp);
return L2k;
};
最佳答案
在您尝试删除元素之前,您的列表可能有问题。
在删除之前向我们展示格式正确的列表。向我们展示生成该列表的代码。向我们展示 struct el_L2k 的声明。
关于c - 从双链表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23412668/