【发布时间】:2020-10-29 06:17:21
【问题描述】:
假设我在下面有这个列表:
List of CDData
1: Test1
2: Test2
3: Test3
4: Test4
5: Test5
6: Test6
现在我想使用链表从列表中删除第三个:这意味着 免费(从DList(3)中删除); 这是我的功能:
TCD *removeFromDList(int res)
{
int count = 0;
TCD *CDData = First;
CDData->Prev = First;
if (First == NULL)
{
printf("Error\n");
return NULL;
}
while (CDData)
{
count++;
if (count == res)
{
if (count == 1)
{
if (CDData == Last)
Last = NULL;
First = First->Next;
return CDData;
}
else
{
while (CDData != NULL)
{
CDData->Prev = CDData->Next;
if (CDData == Last)
Last = CDData->Prev;
// printf("%s",CDData->Title) I tested here whether my function is going to
// delete the third one or not with the printf() and it's actually printing the third one
// Which means it's correct
return CDData;
}
}
}
else
CDData->Prev = CDData;
CDData = CDData->Next;
}
}
顺便说一下,这就是TCD的定义
typedef struct F
{
char *Title;
struct F *Next;
struct F *Prev;
}TCD;
现在重新打印我的列表后,似乎所有 CDData(整个数据结构)都已被释放。任何想法为什么?
我得到这个作为输出
List of CDData
【问题讨论】:
-
错字:
if (First = NULL) -
两个明显的问题:
First = NULL在条件下,应该是First == NULL吗?其次,如果First是NULL然后CDData->Prev = First取消引用空指针(当您将CDData初始化为First)。 -
天哪,多么愚蠢的错误哈哈抱歉
标签: c struct linked-list doubly-linked-list function-definition