gpt4 book ai didi

c - 从 C 语言的双向链表中删除重复项

转载 作者:行者123 更新时间:2023-11-30 18:58:32 26 4
gpt4 key购买 nike

我正在尝试使用 200-800 之间 SAT 成绩的双向链接列表。我需要从列表中删除所有重复项,即通过删除其所有重复项来确保每个成绩仅出现一次。

#define HIGHEST_GRADE 800

typedef struct dListNode{
int* dataPtr;
struct dListNode* next;
struct dListNode* prev;
}DListNode;

typedef struct dList

{
DListNode* head;
DListNode* tail;
}DList;

void removeDuplicates(DList* lst)
{
int i;
int gradesBucket [numOfGrades];
DListNode* temp;
temp = lst->head;

for(i=200 ; i<HIGHEST_GRADE ; i++) /*creating 600 buckets - each bucket for a grade*/
gradesBucket[i] = FALSE;

while (temp)
{
if ((gradesBucket [*temp->dataPtr]) == TRUE) /*if current grade has already */
/* appeared earlier on the list */
{
deleteFromList (temp); /*delete that grade's cell*/
}
else
gradesBucket[*temp->dataPtr] = TRUE; /* mark grade bucket as true, meaning */
/* the grade already appeared*/
temp = temp->next; /*moving on to next grade*/
}
}

void deleteFromList(DListNode* toRemove)
{
toRemove->prev->next = toRemove->next;
toRemove->next->prev = toRemove->prev;

deAllocateListCell (toRemove);
}

void deAllocateListCell (DListNode* cell)
{
free (cell->dataPtr);
free (cell);
}

请帮助我了解问题所在。

<小时/>

这是修复后的代码,但仍然无法正常工作。现在它可以编译,但屏幕上没有显示任何内容。顺便说一句,我不需要删除头部,因为第一个数字永远不会重复......但我照顾它以防头部为 NULL;
我还将要删除的单元格的前一个单元格发送到函数deleteFromList。它仍然不起作用。有任何想法吗?谢谢!

    void deleteFromList(DList* lst, DListNode*  p)
{

DListNode* del_cell = p->next; /* cell to delete*/

if (p->next->next == NULL) /*if cell to remove is the tail*/
{
deAllocateListCell (p->next); /* freeing current tail */
lst->tail = p; /* p is the new tail */
p->next = NULL; /* tail points to NULL */
}
else /* if cell to remove is not the tail (note: can't be head beacuse no duplicates can be found in the first grade) */
{
p->next = del_cell->next;
del_cell->next->prev = p;
deAllocateListCell (del_cell);
}
}

最佳答案

函数deleteFromList()的代码不考虑(字面意思)边缘情况:删除列表的第一个或最后一个节点。

另外,您的代码取消引用指向已释放节点的指针;指针可能会变得完全无效,或者 free() 函数可能会覆盖其内容(正如 Microsoft Debug C RunTime 所知道的那样)。

关于c - 从 C 语言的双向链表中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16059575/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com