简体   繁体   English

释放一个双链表

[英]Free a double linked list

I'm trying to free a double linked list and my question is if I also need to free all the data and pointers in every node.我正在尝试释放一个双链表,我的问题是我是否还需要释放每个节点中的所有数据和指针。 Thank you.谢谢你。

Function: Function:

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;
    }
}

Structure:结构:

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;

So do I also need to free, in the example, the forward pointer and also the other types as well?那么在示例中,我是否还需要释放前向指针以及其他类型? head and head2 are two different pointers, each points to the start of two different lists. headhead2是两个不同的指针,每个指向两个不同列表的开头。

This way of defining the container is very confusing:这种定义容器的方式非常混乱:

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;

Divide and conquer:分而治之:

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;

With this approach, one loop is enough:使用这种方法,一个循环就足够了:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM