释放一个双链表

Free a double linked list

我正在尝试释放一个双链表,我的问题是我是否还需要释放每个节点中的所有数据和指针。谢谢。

函数:

static void free_list(Room *head, Room *head2) {
    Room *tmp = head;
    Room *tmp2 = head2;
    Room *store;
    Room *store2;
    tmp = head2;
    tmp2 = head;

    printf("\nFreeing trap list...\n");
    sleep(2);
    while (tmp != NULL) {
        store = tmp->pNext;
        free(tmp);
        tmp = store;
    }

    printf("\nFreeing rooms list...\n");
    sleep(2);
    while (tmp2 != NULL) {
        store2 = tmp2->pNext;
        free(tmp2);
        tmp2 = store2;
    }
}

结构:

typedef struct Room {
    struct Room *forward;
    struct Room *left;
    struct Room *right;
    struct Room *previous;
    struct Room *pPrev;
    struct Room *pNext;
    Room_Type Room_Type;
    bool emergency_call;
} Room;

那么我是否还需要在示例中释放前向指针以及其他类型? headhead2 是两个不同的指针,分别指向两个不同列表的开始。

这种定义容器的方式很混乱:

typedef struct Room{
  struct Room* forward;
  struct Room* left;
  struct Room* right;
  struct Room* previous;
  struct Room* pPrev;
  struct Room* pNext;
  Room_Type Room_Type;
  bool emergency_call;
} Room;

分而治之:

typedef struct Node {
  struct Node* pPrev;
  struct Node* pNext;
  Room_Type Room_Type;
  bool emergency_call;
} Node;

typedef struct List {
  struct Node* pHead;
  struct Node* pTail;
} List;

用这种方法,一个循环就够了:

void free_list(List *list)
{
    Node *node = list->pHead;

    while (node != NULL)
    {
        Node *next = node->pNext;

        free(node);
        node = next;
    }
    free(list);
}