我想实现一个基本的char堆栈来增加我对堆栈的理解。林困惑,为什么我能够正确推入堆栈,但我不能弹出形成堆栈,我得到一个seg故障。从char的堆栈流行(char&)fcn
这是我的头文件
#include <iostream>
using namespace std;
class Stack {
public:
Stack(int = 10);
Stack(const Stack&);
~Stack();
Stack& operator=(const Stack&);
bool push(char);
bool pop(char &);
bool empty() const;
bool full() const;
bool clear();
bool operator==(const Stack&) const;
//friend ostream& operator<<(ostream&, const Stack&);
private:
int max;
int top;
int actual; //only used in stack (stay) implementation
char* data;
};
这是相关信息我的执行文件只包括
#include <iostream>
#include "stack.h"
using namespace std;
const int MAX = 9;
Stack::Stack(int a) {
max = a;
char *data = new char[a];
int top = 0;
}
Stack::~Stack()
{
delete[] data;
data = NULL;
}
bool Stack::push(char c)
{
if(top==9)
{
cout << "stack is full" <<endl;
return false;
}
else
top++;
return c;
}
bool Stack::pop(char &c)
{
if(top==-1)
{
cout << "Stack is empty" << endl;
return false;
}
c = data[top];
top--;
return c;
}
这里是我的测试文件
#include <iostream>
#include "stack.h"
//#include "queue.h"
using namespace std;
int main()
{
Stack *stack = new Stack(10);
char s = 's';
char t = 't';
char a = 'a';
char c = 'c';
char k = 'k';
stack->push(s);
stack->push(t);
stack->push(a);
stack->push(c);
stack->push(k);
// this is where it seg faults
stack->pop(s);
stack->pop(t);
stack->pop(a);
return 0;
}
您将'top'初始化为0,但您测试它是否等于-1以确定它是否为空。其中之一是不正确的。正如所写,你可以构建一个'Stack',然后立即调用'pop()'(理论上)成功。你的'push()'也不会真正把传入的值放到你的数组中。 – cdhowie 2014-11-03 23:56:20
@cdhowie我修正了我的初始化,肯定是一个错字。我如何修改推送实际值,并弹出一个值? – matt 2014-11-03 23:58:47