[英]Why is my tail still pointing to Something instead of pointing to NULL after I destroy the list
所以我用c編寫了這段代碼,執行基本的雙向鏈接列表任務,例如創建列表,在給定當前NODE之前/之后插入一個節點,刪除給定當前Node,依此類推,但是在嘗試銷毀該對象時遇到了這個問題名單。 發生的是,當我銷毀列表時,它會正確地重新分配所有節點(至少我從調試器監視中看到的那樣),但是當我檢查頭和尾指針是否指向NULL時,因為Nodes no如果不再存在,則頭部指向NULL,但是我的尾部仍然指向某個東西,我不確定這是列表中的節點是否未正確釋放,還是其他原因。
有人可以告訴我發生了什么事嗎? 這是相關代碼;
這是取消分配所有節點的功能,從而破壞了列表
void DListDestruct(DList* list) {
DListNode* tempHead = list->head;;
while (tempHead != NULL) {
tempHead = tempHead->next;
free(list->head);
list->head = tempHead;
}
if (list->tail == NULL) {
list->size = 0;
}
}
//Creation of the structs for the list
typedef struct DListNode_struct {
char *str;
int blankIndex;
int blankLength;
struct DListNode_struct *next;
struct DListNode_struct *prev;
} DListNode;
typedef struct DList_struct {
int size;
DListNode *head;
DListNode *tail;
} DList;
/* This creates a new list and initializes the head/tail */
void DListConstruct(DList* list) {
list->head = NULL;
list->tail = NULL;
list->size = 0;
}
/* inserts newNode after the given currNode */
void DListInsertAfter(DList* list, DListNode* currNode, DListNode* newNode) {
DListNode* sucNode = NULL;
if (list->head == NULL) {
list->head = newNode;
list->tail = newNode;
list->size = list->size++;
}
else if (currNode == list->tail) {
list->tail->next = newNode;
newNode->prev = list->tail;
list->tail = newNode;
list->size = list->size++;
}
else {
sucNode = currNode->next;
newNode->next = sucNode;
newNode->prev = currNode;
currNode->next = newNode;
sucNode->prev = newNode;
list->size = list->size++;
}
}
/* inserts newNode before the given currNode */
void DListInsertBefore(DList* list, DListNode* currNode, DListNode* newNode) {
DListNode* predNode;
if (list->head == NULL) {
list->head = newNode;
list->tail = newNode;
list->size = list->size++;
}
else if (currNode->prev != NULL) {
predNode = currNode->prev;
newNode->next = currNode;
newNode->prev = predNode;
currNode->prev = newNode;
predNode->next = newNode;
list->size = list->size++;
}
else if (currNode->prev == NULL) {
newNode->next = currNode;
currNode->prev = newNode;
list->head = newNode;
list->size = list->size++;
}
}
再說一遍,為什么當我使用DListDestroy函數(第一個在頂部)銷毀List時,所有節點都被釋放了,頭指針指向NULL,而尾指針仍然指向某個東西?
提前致謝!
那是因為尾部stil指向您釋放的節點的地址,所以現在它指向了一些垃圾。
頭指向“ tempHead”所指向的任何位置,並且在循環結束時它指向null,因為在插入過程中,您將null放置在最后一個節點的下一個節點中。
總之,尾部指向最后一個節點的地址,這是垃圾。 頭指向最后一個節點的下一個為NULL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.