C ++中的循环链表的析构函数?

阿德南·麻雀(Adnan Sparrow)

当为此循环单链表调用“类LL”〜LL()的析构函数时,程序崩溃,而不是释放指针的堆空间。我怎么解决这个问题?

class Node {
public:
  int data;
  Node *next;
};

class LL {
private:
  Node *head, *tail;

public:
  LL() {
    head = NULL;
    tail = NULL;
  }
  // destructor
  ~LL() {
    Node *p = head;
    while (p->next != head) {
      p = p->next;
    }

    while (p != head) {
      p->next = head->next;
      delete head;
      head = p->next;
    }

    if (p == head) {
      delete head;
      head = nullptr;
    }
  }

  // circular singly Linked list

  void createLL() {
    int n, x;
    cin >> n;

    for (int i = 0; i < n; i++) {
      cin >> x;

      Node *t = new Node;
      t->data = x;
      t->next = NULL;

      if (head == NULL) {
        head = tail = t;
      } else {
        tail->next = t;
        tail = t;
      }
    }
    tail->next = head;
  }
龙虾

链接列表存在一些问题。

  1. 链表的析构函数假设head不为null(如果有可能)。在尝试清理内存之前,请确保检查head不为null。一旦完成,看起来您原来的析构函数应该可以工作了。
  2. 如果用户输入的大小小于或等于0,则createLL函数将调用未定义的行为。 tail->next = head;
  3. TreateLL用词不当,因为它实际上并没有按照预期的意义“创建”新列表。内容不会清除,因此n元素会附加到当前列表的末尾。
  4. 同样,仅使用一个尾指针就可以创建循环链接列表。

但是,使循环链接列表的实现生效的过程看起来像这样

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;
};
class LL {
private:
    Node* head, * tail;
public:
    LL() : head(nullptr),
        tail(nullptr) {
    }
    ~LL() {
        if (head) {
            Node* p = tail;

            while (p != head) {
                p->next = head->next;
                delete head;
                head = p->next;
            }
            if (p == head) {
                delete head;
                head = nullptr;
            }
        }
    }

    void storeUserInput() {
        int n, x;
        cin >> n;
        if (n <= 0) {
            return; //no input to retrieve.
        }
        for (int i = 0; i < n; i++) {
            cin >> x;
            Node* t = new Node;
            t->data = x;
            t->next = nullptr;

            if (head == nullptr) {
                head = tail = t;
            }
            else {
                tail->next = t;
                tail = t;
            }
        }
        tail->next = head;
    }

};
int main() {
    LL l;
    l.storeUserInput();

    char response;
    std::cin >> response;
}

似乎您可以访问C ++ 11或更高版本的编译器,如果是这样,则应使用nullptr代替NULL,因为它是确定的指针类型。在这里查看更多

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章