#include<iostream>using namespace std;class MyStack {public: MyStack(int Size); ~MyStack(); bool stackEmpty(); bool stackFull(); void clearStack(); int stackLength(); //char push(char elem); bool push(char elem); bool pop(char &elem); void stackTravel();private: int size; int top; char *pStack;}; MyStack::MyStack(int Size){ size=0; top=0; size = Size; pStack = new char(Size); cout<<"申请"<<size<<"个内存的空间!"<<endl;}MyStack::~MyStack(){ delete []pStack; pStack=NULL;cout<<"delete"<<endl;}bool MyStack::stackEmpty(){ if (top==0) return true; else return false;}bool MyStack::stackFull(){ if(size==top) return true; else return false;}void MyStack::clearStack(){ top = 0;//覆盖}int MyStack::stackLength(){ return top;}bool MyStack::push(char elem){ if(stackFull()){ return false; } pStack[top]=elem; top++; return true;}bool MyStack::pop(char &elem){ if(!stackEmpty()) { top--; elem=pStack[top]; return true; } else { return false; } }void MyStack::stackTravel(){ for (int i = 0;i < top;i++) { cout << pStack[i]; } cout << endl;}int main() { MyStack pStack(5); char elem; char num[5]={'1','2','3','4','5'}; for(int i=0;i<5;i++){ pStack.push(num[i]); } //pStack.push('p'); //pStack.push('p'); pStack.pop(elem); if (pStack.stackEmpty()) { cout << "The stack is empty"<<endl; } if (pStack.stackFull()) { cout << "The stack is full" << endl; } cout << "The stack's length:" << pStack.stackLength() << endl; /*pStack.push('a'); pStack.push('p'); pStack.push('p'); pStack.push('l');*/ //pStack.push('e'); //pStack.stackTravel(); /*pStack.pop(elem); cout << elem << endl; pStack.clearStack();*/ //cout << "The stack's length:" << pStack.stackLength() << endl; return 0;}
2 回答
下雨何
TA贡献28条经验 获得超23个赞
sorry,不懂c
不过大体上了解一点点,要注意变量的声明和销毁,另外注意变量类型
c不比php,它是强数据类型,不能简单随意的转换数据类型
c不比java,它对内存的控制比较严格,不像java,都叫给虚拟机,不用管这些,同时java也不用考虑指针
建议多了解一点 指针,数据在内存的存放等等
onemoo
TA贡献883条经验 获得超454个赞
在构造函数中,你想申请一块连续size个char内存,是不是?
pStack = new char(Size);
不过上面这代码写错了,申请一块连续内存需要在类型后用中括号 [ ]。 你写成了小括号,这样只是申请了一个char内存,其初值为size而已。
- 2 回答
- 0 关注
- 1430 浏览
添加回答
举报
0/150
提交
取消