//-------------------------------------
// Stack.h
//-------------------------------------
const int SIZE = 10;//size初始化为10
//-------------------------------------
class Stack{
int stck[SIZE]; //holds the stack
int tos; //index of top-of-stack
public:
Stack():tos(0){}//tos即栈的顶部初始化为0
int top();
void push(int ch); //push integer to stack
int pop(); //pop integer from stack.
};//-----------------------------------
//-------------------------------------
// Stack.cpp
//-------------------------------------
#include"Stack.h"
#include<iostream>
//-------------------------------------
int Stack::top()//top(),push(),pop()
{
return stck[tos-1];//无需判断
}//------------------------------------
void Stack::push(int ch){
if(tos==SIZE)//只判断是否已满,进行判断
{
std::cout<<"\nStack is full\n";
return;
}
stck[tos++]=ch;//stck[tos++]=ch;
}//------------------------------------
int Stack::pop()
{
if(tos==0){
std::cout<<"\nStack is empty\n";
return 0; //return null on empty stack.
}
return stck[--tos]; //top of stack,如果最高一层为0,输出empty,如果不为0,返回他的下一个,使下一个数值为顶部
}//------------------------------------
//-------------------------------------
// EX0805.cpp
// 栈应用
//-------------------------------------
#include"Stack.h"
#include<iostream>
//-------------------------------------
int main(){
Stack s;
s.push(10);
s.push(12);
s.push(14);
std::cout<<s.top()<<"\n";
s.pop();
std::cout<<s.top()<<"\n";
system("pause");
}//------------------------------------