Pencil.C++

更新速度可能会晚于http://blog.csdn.net/bilaopao

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  34 随笔 :: 0 文章 :: 40 评论 :: 0 Trackbacks
 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 }

posted on 2009-09-27 20:14 Pencil.C++ 阅读(5686) 评论(0)  编辑 收藏 引用 所属分类: 数据结构与算法

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理