利用数组实现栈,用的是动态数组,直接上代码:
头文件:
class MyStack
{
public:
MyStack(int Capacity);
~MyStack(void);
int IsEmpty();
int IsFull();
void Push(int x);
void Pop();
int Top();
private:
int capacity;//the capacity of stack.
int* myArray;
int topOfStack;//the top of stack.
};
.cpp文件:
#include "StdAfx.h" #include "MyStack.h" #include <iostream> #include <stdexcept> using std::cin; using std::cout; using std::endl; using std::runtime_error; MyStack::MyStack(int Capacity):topOfStack(-1) { /*if(Capacity<5) { Error("Stack size is too small"); }*/ while(Capacity<5) { cout<<"Stack size is too small,please enter it again"<<endl; } capacity = Capacity; myArray = new int[size_t(Capacity)]; if(myArray==NULL) { runtime_error("Out of space"); } } MyStack::~MyStack(void) { delete [] myArray; } int MyStack::IsEmpty() { return topOfStack == -1; } int MyStack::IsFull() { return topOfStack == (capacity-1); } void MyStack::Push(int x) { if(this->IsFull()) { runtime_error("Full Stack"); } else { topOfStack++; *(++myArray) = x; //myArray[++topOfStack] = x; } } void MyStack::Pop() { if(this->IsEmpty()) { runtime_error("Empty Stack"); } else { topOfStack--; *myArray = NULL; myArray--; } } int MyStack::Top() { if(this->IsEmpty()) { runtime_error("Empty Stack"); return 0; } else { topOfStack--; return *myArray--; } }
代码经过测试,可用。