/*--Stack.h------------------------------------------------*/
#pragma once
#include <iostream>
#ifndef STACK
#define STACK
const int STACK_CAPACITY =128;
typedef int StackElement;
class Stack
{
public:
Stack(void); //构造函数
bool empty() const; //检查栈是否为空
void push(const StackElement & value); //通过栈顶添加一个元素来修改栈
void display(ostream & out) const; //显示所有的栈元素
StackElement top() const; //提取栈顶元素
void pop(); //通过删除栈顶元素来修改栈
private:
StackElement myArray[STACK_CAPACITY];
int myTop;
};
#endif
/*--Stack.cpp-----包含Stack成员函数的实现------------------*/
#include <iostream>
using namespace std;
#include "Stack.h"
Stack::Stack(void):myTop(-1) //初始化构造函数
{
}
bool Stack::empty() const //判断是否为空栈
{
return -1==myTop;
}
void Stack::push(const StackElement & value) //将元素压入栈中
{
if(myTop < STACK_CAPACITY -1) //栈未满
{
++myTop;
myArray[myTop] = value;
}
else
{
cerr<<"***Stack full -- can't add new value ***\n"
"Must increase value of SACK_CAPACITY in Stack.h \n";
exit(1);
}
}
void Stack::display(ostream & out) const //显示栈全部元素
{
for(int i = myTop; i >=0; i--)
{
cout<<myArray[i]<<endl;
}
}
StackElement Stack::top() const //返回栈顶元素
{
if(!empty()) //非空
{
return (myArray[myTop]);
}
else
{
cerr<<"*** Stack is empty--return garbage \n";
return rand(); //返回一个随机数
}
}
void Stack::pop() //弹出栈顶元素
{
if(!empty()) //栈非空
{
myTop--;
}
else
{
cerr<<"*** Stack is empty -- can't remove a value ***\n";
}
}
/*--测试 Stack 类 ----------------------------------------*/
#include <iostream>
using namespace std;
#include "Stack.h"
int main()
{
Stack s;
cout<<"Stack created. Empty? "<<boolalpha<<s.empty()<<endl;
cout<<"How many elements to add to the stack? ";
int numItems;
cin>>numItems; //指定栈中元素个数
for(int i = 1; i <= numItems; i++) //入栈
s.push(i);
cout<<"Stack contents: \n";
s.display(cout); //显示栈的全部元素
cout<<"Stack empty?"<<s.empty()<<endl;
cout<<"Top value: "<<s.top()<<endl;
while(!s.empty())
{
cout<<"Popping "<<s.top()<<endl;
s.pop();
}
cout<<"Stack empty? "<<s.empty()<<endl;
cout<<"Top value: "<<s.top()<<endl;
cout<<"Trying to pop: "<<endl;
s.pop();
return 0;
}