【问题标题】:C++ function that deletes dynamic linked list删除动态链表的 C++ 函数
【发布时间】:2022-11-04 19:14:27
【问题描述】:

我目前正在做一个类项目,我们在其中创建一个链接列表,我们应该创建一个清除列表然后删除它的函数(使用“delete LIST_NAME;”)。我已经按照教授的指示实现了该功能,还强制列表在删除后变为空。该函数在其自身内部工作,但当它返回主函数时,列表会获得一个新值。

这种功能在 C++ 中是不可能的吗?

#include <iostream>

struct Node 
{
  int val;
  Node* next;
};

struct LinkedList
{
  int count;
  Node* head;
  Node* tail;
};

void Clear(LinkedList* list) {
  Node* node = list->head;
  Node* next = nullptr;

  while (node != nullptr) {
    next = node->next;
    delete node;
    node = next;
  }
  list->head = nullptr;
  list->tail = nullptr;
  list->count = 0;
}

void Destroy (LinkedList* list) {
  Clear(list);
  delete list;
  list = nullptr;
  std::cout << "\n(should be) Destroyed";
}

int main() {
  //creating a list element
  Node* node = new Node;
  node->val = 'a';
  node->next = nullptr;

  //inserting the element onto list
  LinkedList* list  = new LinkedList;
  list->count = 0;
  list->head = node;
  list->tail = node;

  std::cout << "\nList: " << list;

  Destroy(list);
  
  std::cout << "\nList: " << list;

  std::cout << "\nEND";
  
}

这只是我的代码的一个片段,但它说明了我的意思。使用调试器,该列表在函数末尾的值为 0x0,但在主函数中,它被分配了一个新值,如调试器所示。

【问题讨论】:

  • 参数是按值传递的,也是指针。
  • Destroy 函数内部,变量list 是一个当地的函数的变量。它的初始值为复制您在通话中使用的那个。修改局部变量不会修改调用中使用的原始值。您需要通过参考.
  • 你听说过构造函数和析构函数吗?
  • @propelledaviator 你明白我的回答吗?如果不是,请要求澄清。
  • 从技术上讲,您已经在显示的代码中使用了两个类:structclass 相同,但默认为 public 可见性。

标签: c++


【解决方案1】:

您按值获取list,因此它是函数的本地变量。

如果您想对其在呼叫站点可见的更改进行更改,请参考:

// `list` is now a reference to the pointer at the call site:
void Destroy(LinkedList*& list) {
    Clear(list);
    delete list;
    list = nullptr; // this now sets the referenced `LinkedList*` to `nullptr`
    std::cout << "
(should be) Destroyed";
}

【讨论】:

  • 效果很好!非常感谢
  • @propelledaviator 太棒了!别客气!
猜你喜欢
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
  • 2016-07-06
  • 2020-12-18
  • 2014-03-04
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
相关资源
最近更新 更多