gpt4 book ai didi

c++ - 堆栈推送操作实现不起作用

转载 作者:行者123 更新时间:2023-11-28 06:51:27 24 4
gpt4 key购买 nike

我正在编写自己的堆栈来练习语言和练习指针。我使用链表来表示堆栈而不是数组。 push 操作只是将 top nodes 值分配给每个节点,我不明白为什么,我尝试编写一个赋值运算符但它没有做任何事情。

template <class T>
void stack<T>::push(T data) {

//Operation to preform if the stack is empty.
//Root element is popped off last (First in, Last out)
if ( empty() ) {
root_node = new node;
root_node->node_data = data;
root_node->next = nullptr;
elements++;
}

//Operation to preform if stack is not empty.
//Elements inserted into stack with dynamic allocation.
else {
node *new_node = new node;


/* PROBLEM AREA */

new_node = root_node;
root_node->next = new_node;
root_node->node_data = data;

elements++;
}

这是节点结构

struct node {     //Definition of node structure with constructor and destructor

T node_data;
node *next;

//default ctor
node() { next = nullptr; }

//default dtor
~node() { delete root_node; }

node operator=(const node &rhs) {
if ( this != &rhs) {
this->next = rhs->next;
this->node_data = rhs->node_data;
}
return *this;
}
};

按下 10、20、40、30 并弹出它们并调用 top() 时的输出

Top element 30

Current Top Element: 30 size of stack 3
Current Top Element: 30 size of stack 2
Current Top Element: 30 size of stack 1

最佳答案

重载的operator=是错误的。你有:

node operator=(const node &rhs) {

所以它按值返回一个拷贝。您没有定义复制构造函数,因此这将是一个会导致问题的“浅拷贝”。

定义operator=的常用方法是

node& operator=(const node &rhs) {

然而,这个函数里面的逻辑也没有意义:

    if ( this != &rhs) {
this->next = rhs->next;
this->node_data = rhs->node_data;
}

现在您将拥有 2 个节点,它们都指向相同的 next。所以你不再有一个列表,你有某种倒挂的树。


您应该实现或删除/私有(private)您的复制构造函数,以消除发生意外浅拷贝的可能性。


另一个大问题是:

node *new_node = new node; 
new_node = root_node;

您创建了一个新节点,但随后您立即泄漏了该内存并使new_node 指向root_node。根据您的描述,我怀疑您的意思是:

*new_node = *root_node;

这意味着 new_node->operator=(*root_node); 调用你的 operator= 函数。


总而言之,整个事情一团糟,你最好从头开始重做。我建议将您的代码分为两部分:

  • 链表
  • 堆栈逻辑

自行编写链表并检查其是否有效。 (这应该是一个类)

一旦完成,您就可以在链表的顶部执行堆栈实现。

关于c++ - 堆栈推送操作实现不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23879148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com