栈是一种非常简单的数据结构,直接贴代码了:
1.头文件stack.h
// stack.h -- class definition for the stack ADT
#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;
// push() returns false if stack already is full, ture otherwise
bool push(const Item & item); // add item to stack
// pop() returns false if stack already is empty, ture otherwise
bool pop(Item & item);
};
#endif
2.类函数定义stack.cpp
// stack.cpp -- Stack member functions
#include "stack.h"
Stack::Stack()
{
top = 0;
}
bool Stack::isempty() const
{
return 0 == top;
}
bool Stack::isfull() const
{
return MAX == top;
}
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;
}
3.测试,模拟售货员的行为——先处理篮子里最上面的物品
// stacker.cpp -- testing the Stack class
#include <stdio.h> //个人喜欢c语言的输入和输出
#include <ctype.h> // or cctype for c++
#include <stdlib.h>
#include "stack.h"
int main()
{
Stack st;
char ch;
unsigned long po;
printf("Please enter A to add a purchase order,\n");
printf("P to process a PO, or Q to quit.\n");
while((1 == scanf("%c", &ch)) && ch != 'Q' && ch != 'q')
{
if(!isalpha(ch))
{
printf("\aOrder: P or Q !\n");
continue;
}
switch(ch)
{
case 'A':
case 'a':
printf("Enter a PO number to add: ");
scanf("%d", &po);
if(st.isfull())
printf("Stack already full\n");
else
st.push(po);
break;
case 'P':
case 'p':
if(st.isempty())
printf("stack already empty\n");
else
{
st.pop(po);
printf("PO #%d popped\n", po);
}
break;
}
// 清除空白字符,必须放到后面,因为swith中有输入,会留下回车符
while(getchar() != '\n')
continue;
printf("Please enter A to add a purchase order,\n");
printf("P to process a PD, or Q to quit.\n");
}
printf("Bye!\n");
system("pause");
return 0;
}