一个简单的栈的实现
stack.h //栈数据结构的类定义
#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
typedef unsigned long Item;
class Stack
{
private:
enum{MAX=10}; //栈的大小
Item items[MAX]; //保存栈的数据的数组
int top; //指向栈顶的索引
public:
Stack();
~Stack();
bool isEmpty()const;
bool isFull()const;
//push() 如果栈已满返回false,否则返回true
bool push(const Item& item);
//pop() r如果栈为空返回false,否则返回true
bool pop(Item& item);
};
#endif // STACK_H_INCLUDED
stack.cpp
//栈的具体实现
#include"stack.h"
Stack::Stack()
{
top=0;
}
Stack::~Stack()
{
}
bool Stack::isEmpty()const
{
return top==0;
}
bool Stack::Stack::isFull()const
{
return top==MAX;
}
bool Stack::push(const Item& item)
{
if(top<MAX)
{
items[top++]=item;
return true;
}
else
{
return false;
}
}
bool Stack::pop(Item& item)
{
if(top>0)
{
item=items[--top];
return true;
}
else
{
return false;
}
}
main.cpp //验证栈是否可用
#include <iostream>
#include "stack.h"
using namespace std;
int main()
{
Stack stack1;
char ch;
unsigned long po;
cout<<"输入A添加数据"<<endl
<<"输入P弹出数据,Q退出"<<endl;
while(cin>>ch&&toupper(ch)!='Q')
{
while(cin.get()!='\n')<span style="white-space:pre"> </span>//删除输入行剩余数字
continue;
if(!isalpha(ch))
{
cout<<"请输入正确的字符"<<endl;
continue;
}
switch(ch)
{
case 'A':
case 'a':
cout<<"输入一个整数添加到栈: ";
cin>>po;
if(stack1.isFull())
cout<<"栈已满,会溢出!"<<endl;
else
stack1.push(po);
break;
case 'p':
case 'P':
if(stack1.isEmpty())
cout<<"栈为空,请确保栈中已有数据!"<<endl;
else
{
stack1.pop(po);
cout<<"POP #"<<po<<" 弹出!"<<endl;
}
break;
}
cout<<"输入A添加数据"<<endl
<<"输入P弹出数据,Q退出"<<endl;
}
cout<<"Bye!"<<endl;
return 0;
}
结果如图: