【发布时间】:2014-05-26 23:54:25
【问题描述】:
我正在编写自己的堆栈来练习语言和练习指针。我使用链表来表示堆栈而不是数组。推送操作只是将顶部节点的值分配给每个节点,我不知道为什么,我尝试编写一个赋值运算符但它没有做任何事情。
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
【问题讨论】:
-
'这是我得到的输出 If ...' 嗯嗯什么?我找不到任何输出样本? (正确格式化代码避免任何滚动条,也可能有助于提高可读性!!)
-
new_node = root_node;你刚刚分配的new node现在永远丢失了。 -
感谢您的建议。已编辑。
-
您的
root_node永远不会改变,但root_node->node_data = data;会不断改变数据 -
@Revoo 您将一个新节点分配给
new_node,然后在下一行您将root_node分配给new_node,没有其他内容指向新节点,因此它不能再已检索。
标签: c++ pointers stack implementation