1 #include<iostream.h>
2 const int MAX=5; //假定棧中最多保存5個數據
3 //定義名為stack的類,其具有棧功能
4 class stack {
5 //數據成員
6 float num[MAX]; //存放棧數據的數組
7 int top; //指示棧頂位置的變量
8 public:
9 //成員函數
10 void init(void) { top=0; } //初始化函數
11 void push(float x) //入棧函數
12 {
13 if (top==MAX){
14 cout<<"Stack is full !"<<endl;
15 return;
16 };
17 num[top]=x;
18 top++;
19 }
20 float pop(void) //出棧函數
21 {
22 top--;
23 if (top<0){
24 cout<<"Stack is underflow !"<<endl;
25 return 0;
26 };
27 return num[top];
28 }
29 }
30 //以下是main()函數,其用stack類創建棧對象,并使用了這些對象
31 main(void)
32 {
33 //聲明變量和對象
34 int i;
35 float x;
36 stack a,b; //聲明(創建)棧對象
37 //以下對棧對象初始化
38 a.init();
39 b.init();
40 //以下利用循環和push()成員函數將2,4,6,8,10依次入a棧對象
41 for (i=1; i<=MAX; i++)
42 a.push(2*i);
43 //以下利用循環和pop()成員函數依次彈出a棧中的數據并顯示
44 for (i=1; i<=MAX; i++)
45 cout<<a.pop()<<" ";
46 cout<<endl;
47 //以下利用循環和push()成員函數將鍵盤輸入的數據依次入b棧
48 cout<<"Please input five numbers."<<endl;
49 for (i=1; i<=MAX; i++) {
50 cin>>x;
51 b.push(x);
52 }
53
54 //以下利用循環和pop()成員函數依次彈出b棧中的數據并顯示
55 for (i=1; i<=MAX; i++)
56 cout<<b.pop()<<" ";
57 }