申明:   转自    http://www.cnblogs.com/pengshao/archive/2011/12/26/2301461.html

头文件stackDemo.h

 #pragma once//常用C++杂注,头文件最开始加入,能够保证头文件只被编译一次
typedef int DataType;
const int MaxStatckSize = ; //定义栈的大小
class StackDemo
{
public:
//析构造函数
StackDemo(void);
~StackDemo(void); //压栈出栈操作
void Push( DataType item);
DataType Pop(void);
void ClearStack(void); //访问栈顶,返回栈顶当前下标
DataType Peek(void)const; //检测椎栈
bool isEmpty(void)const;
bool isFull(void)const; private:
DataType stacklist[MaxStatckSize];
int tos;//栈顶
};

实现 stackDemo.cpp

 #include "StackDemo.h"
#include <iostream>
using namespace std;
StackDemo::StackDemo(void)
{
this->tos = -;
}
StackDemo::~StackDemo(void)
{
this->tos = -;
}
void StackDemo::Push( DataType item)
{
//栈是否已满
if (!isFull())
{
tos++;
this->stacklist[tos] = item; }
else
cout << "Out of the Stack!" << endl;
} DataType StackDemo::Pop(void)
{
if (!isEmpty())
{
int ebp = tos;
tos --;
return stacklist[ebp];
}
else
return -;
} DataType StackDemo::Peek(void)const
{
return tos;
} void StackDemo::ClearStack()
{
for (int i = tos; i >= ; i--)
stacklist[i] = ;
tos = -;
cout << "Clear stack done!" << endl;
} bool StackDemo::isFull(void)const
{
return tos > MaxStatckSize ? true : false;
} bool StackDemo::isEmpty(void)const
{
return tos < ? true : false;
}

main.cpp

 #include <iostream>
#include "StackDemo.h"
using namespace std; int main()
{
StackDemo *sd = new StackDemo();
sd->Push();//压栈
sd->Push();//压栈
sd->Push();//压栈
cout << "Stack TOP:" << sd->Peek() << endl;
for(int i=;i<;i++)
cout << "POP:" << sd->Pop() << endl; cout << "Stack TOP:" << sd->Peek() << endl; return ; }

  

05-11 13:42