栈push操作实现不工作

Stack push operation implementation not working

本文关键字:工作 实现 操作 push      更新时间:2023-10-16

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

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。所以你不再有一个列表,你有某种颠倒的树。


您应该实现或delete/private您的复制构造函数,以消除意外的浅复制发生的可能性。


另一个大问题是:

node *new_node = new node; 
new_node = root_node; 

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

*new_node = *root_node;

表示new_node->operator=(*root_node);调用operator=函数。


总之,整件事是如此的混乱,你可能最好从头开始。我建议将代码分成两部分:

  • 链表
  • 栈逻辑

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

一旦完成,你就可以在链表上做你的堆栈实现了。

您在else部分(您的问题所在)以错误的顺序进行分配。第二个语句立即破坏了新分配的节点。你应该有:

node *new_node = new node;
new_node->node_data = data;
new_node->next = root_node->next;
root_node = new_node;
elements++;