栈push操作实现不工作
Stack push operation implementation not working
我正在写我自己的堆栈来练习语言和练习指针。我使用链表来表示堆栈,而不是数组。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++;
相关文章:
- CV_OCL_RUN宏如何在OpenCV(版本3.4.5)的goodFeaturesToTrack实现中工作?
- 实现 DFS 在较短的输入下工作正常,但在较大的输入下会抛出分段错误
- nth_element基于修改后的quick_sort实现,无法按预期工作
- 这个数组交集的实现是如何工作的
- 查找表究竟是如何工作的,以及如何实现它们
- 只有第一个缓冲区可以在C++中实现的Double缓冲区中工作
- 尝试实现二叉搜索算法,似乎无法使其工作
- popen() 如何工作以及如何在 Linux 上实现它到 C++ 代码中
- opengl32.lib如何在Windows(仅1.1版本)上工作?它是否真正实现了OpenGL函数
- 在 gcc 上自己的元组实现段错误,同时在 clang 中工作
- 运算符 [] 函数的实现是如何工作的
- 如何以相同的方法在子类中超载的相同方法来实现工作变量参数方法
- 实现快速排序,几乎可以工作但不能
- 在Graph实现中,对和向量是如何工作的
- 在C 中实现此类工作流程的最佳方法
- 这种珠子排序算法的 c++ 实现是如何工作的
- 有可能实现一个与数组而不是单个对象一起工作的内存池吗
- 我正试图在我的SFML Platformer中实现双跳,但它并没有按预期的方式工作
- C++,当每个工作线程都必须执行几个不同的任务时,如何为任务实现线程池
- 解释在opencv中实现的阴影检测代码的工作原理