为什么我的尾部仍然指向Something而不是在我销毁列表后指向NULL

时间:2016-10-06 20:32:26

标签: c list linked-list doubly-linked-list destroy

所以我在c中编写了这个代码来执行基本的双向链接列表任务,比如创建列表,在给定的当前NODE之后/之前插入节点,删除给定的当前节点等等,但是当我遇到这个问题时我遇到了这个问题试图摧毁这份名单。发生的事情是,当我销毁列表时,它正确地释放所有节点(至少我从调试器手表中看到的那样),但是当我检查头节点和尾节指针是否指向NULL,因为节点没有更长的存在,头指向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,但尾指针仍指向某个东西?

提前致谢!

1 个答案:

答案 0 :(得分:0)

那是因为tail stil指向你释放的节点的地址,所以现在它指向一些垃圾。

头部指向“tempHead”指向的任何位置,并且在循环结束时它指向null,因为在插入过程中,您将null放在最后一个节点的下一个中。

总之,尾部指向最后一个节点的地址,即垃圾。 头部指向最后一个节点的下一个节点。