数组堆栈 (例子)
//////////////////////////////////////stack.h///////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
#ifndef STACK_H_
#define STACK_H_
typedef unsigned long Item;
class Stack
{
private:
enum {MAX=10};
Item items[MAX];
int top;
public:
Stack();
bool isempty()const;
bool isfull()const;
bool push(const Item & item);
bool pop(Item & item);
};
#endif
//////////////////////////////////////stack.cpp//////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
#include "stack.h"
Stack::Stack()
{
top=0;
}
bool Stack::isempty()const
{
return top==0;
}
bool 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;
}
///////////////////////////mian.cpp////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <cctype>
#include "stack.h"
int main()
{
using namespace std;
Stack st;
char ch;
unsigned long po;
cout<<"please enter A to a purchase order,\n"
<<"P to process a PO,or Q to quit.\n";
while (cin>>ch&&toupper(ch)!='Q')
{
while (cin.get()!='\n')
continue;
if (!isalpha(ch))
{
cout<<'\a';
continue;
}
switch (ch)
{
case 'A':
case 'a':
cout<<"enter a PO number to add:";
cin>>po;
if (st.isfull())
cout<<"stack already full\n";
else
st.push(po);
break;
case 'p':
case 'P':if (st.isempty())
cout<<"stack already empty\n";
else
{
st.pop(po);
cout<<"po#"<<po<<" popped\n";
}
break;
}
cout<<"please enter A to a purchase order,\n"
<<"P to process a PO,or Q to quit.\n";
}
cout<<"bye\n";
return 0;
}


浙公网安备 33010602011771号