[英]Deleting Duplicates From a Doubly Linked List in C
我正在嘗試使用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()
的代碼deleteFromList()
字面) deleteFromList()
情況:刪除列表的第一個或最后一個節點。
另外,您的代碼取消了指向已釋放節點的指針的引用; 指針可能變得完全無效,或者free()
函數可以覆蓋其內容(如Microsoft Debug C RunTime所知)。
嘗試具體-什么是行不通的? 您的代碼可以編譯嗎? 您在運行時收到錯誤消息嗎? 您沒有獲得場景中預期的結果嗎?
您的deleteFromList
函數應注意刪除頭部或尾部(即toRemove->prev
或toRemove->next
分別為null時)。
temp = lst->head;
當lst
為null時會發生什么? 您會收到運行時錯誤
如果刪除head
或tail
,則不會更新
這就是我乍看之下的發現。
您應該編寫while(temp->next)
來更正此問題。...而且您也可以使用free簡單地釋放節點。 並消除懸空指針問題,請在釋放該節點后將其設置為NULL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.