【发布时间】:2014-09-01 12:07:59
【问题描述】:
这是我使用带有结构类型节点和类类型堆栈的模板的堆栈实现:
堆栈.h
#ifndef STACK_H_
#define STACK_H_
#include <cstdlib>
#include <iostream>
#include <cassert>
using namespace std;
template <class t>
struct node{
t data;
node<t>* next;
};
template <class t>
class stack
{
public:
stack();
~stack();
bool isEmpty(){ return (top_ptr=NULL);};
void push(const t&);
void pop();
t top() const;
void reverse();
void clear();
void print();
private:
node<t>* top_ptr;
};
template <class t>
stack<t>::stack()
{
top_ptr=NULL;
}
template <class t>
stack<t>::~stack()
{
while(top_ptr != NULL) pop();
}
template <class t>
void stack<t>::push(const t& source)
{
node<t>* new_node = new node<t>;
new_node->data = source;
new_node->next = top_ptr;
top_ptr = new_node;
cout << "Inserito!" << endl;
}
template <class t>
void stack<t>::pop()
{
node<t>* remove = top_ptr;
top_ptr = top_ptr->next;
delete remove;
cout << "Rimosso!" << endl;
}
template <class t>
t stack<t>::top() const
{
assert(top_ptr != NULL);
return top_ptr->data;
}
template <class t>
void stack<t>::clear()
{
node<t>* temp;
while(top_ptr != NULL)
{
temp = top_ptr;
top_ptr = top_ptr->next;
delete temp;
}
cout << "Clear completato!" << endl;
}
template <class t>
void stack<t>::reverse()
{
stack<t> new_stack;
while(top_ptr != NULL)
{
new_stack.push(top_ptr->data);
pop();
}
cout << "Reverse completato!" << endl;
}
template <class t>
void stack<t>::print()
{
node<t>* ptr = top_ptr;
while(ptr!=NULL)
{
cout << " " << ptr->data << endl;
ptr = ptr->next;
}
}
#endif /* STACK_H_ */
这是 main.cpp:
#include "stack.h"
int main()
{
stack<int> stackino;
for(int i = 0; i<10; i++) stackino.push(i);
stackino.pop();
cout << "top(): " << stackino.top() << endl;
stackino.print();
cout << "Invoco clear()" << endl;
stackino.clear();
cout << "Stackino dopo clear():" << endl;
stackino.print();
cout << "Invoco reverse()" << endl;
stackino.reverse();
cout << "Stackino dopo reverse()" << endl;
stackino.print();
cout << "FINE!" << endl;
return 0;
}
问题是导致程序崩溃的reverse(),我猜“top_ptr = new_stack.top_ptr”是错误的,但它可以编译和执行,但会崩溃。有人可以帮我纠正这个吗?
【问题讨论】:
-
你的
isEmpty函数不正确,首先... -
要扩展上述评论
top_ptr=NULL将设置top_ptr为NULL(BAD) 并返回false,将其更改为==。 -
无法复制。在 Clang、GCC 和 VC++ 下运行良好。必须是未定义的行为或代码中的其他位置。
-
@djanthony93 “崩溃”是什么意思?它实际上是段错误还是类似的东西?
标签: c++ function stack reverse