实现堆栈类 Stack。
class Stack{
public:
void init (unsigned int ); // 堆栈初始化方法
void cleanup();
bool pop(); // 弹栈操作
bool push(int); // 压栈操作
int readTop(); // 读栈顶元素
bool isEmpty(); // 判断栈是否为空
private:
int * data; // 存储栈数据的数组
unsigned int top; // 栈顶元素下标
unsigned int size; // 栈的最大容量
public:
static unsigned int objNum; // 静态成员,当前存在的 Stack 对象数目
static unsigned int defSize; // 静态成员,栈的缺省大小
} ;
init(n) 用来初始化一个大小为 n 的堆栈;
cleanup() 用来销毁当前堆栈;
push(v) 完成将值 v 压入堆栈;
pop() 用来弹出当前栈顶元素;
readTop() 用来读取当前栈顶元素;
isEmpty() 用来判断当前栈是否为空;
top 和 size 分别记录了当前栈顶位置与堆栈大小。
#include <iostream>
using namespace std;
class Stack{
public:
void init (unsigned int );
void cleanup();
bool pop();
bool push(int);
int readTop();
bool isEmpty();
private:
int * data;
unsigned int top;
unsigned int size;
public:
static unsigned int objNum;
static unsigned int defSize;
} ;
unsigned int Stack::objNum = 0;
unsigned int Stack::defSize = 20;
/*********** begin **************/
void Stack::init(unsigned int sz)
{
this->size = sz;
this->data = new int[sz];
this->top = 0;
}
void Stack::cleanup()
{
delete this->data;
this->data = NULL;
}
bool Stack::pop()
{
if(this->top == 0) return false;
this->top--;
return true;
}
bool Stack::push(int k)
{
if(this->top == this->size) return false;
this->data[this->top] = k;
this->top++;
return true;
}
int Stack::readTop()
{
return this->data[this->top - 1];
}
bool Stack::isEmpty()
{
return this->top == 0;
}
/*********** end **************/
#define N 10
int main(int argc, char** argv){
Stack s;
int v;
s.init(N+1);
for (int i=0; i<N; i++){
cin >> v;
s.push(v);
}
for(int i=0; i<N; i++){
cout << s.readTop()<<endl;
s.pop();
}
return 0;
}