[转载]C++堆栈的入门学习

申明:   转自    http://www.cnblogs.com/pengshao/archive/2011/12/26/2301461.html

 

头文件stackDemo.h

 1 #pragma once//常用C++杂注,头文件最开始加入,能够保证头文件只被编译一次
 2 typedef int DataType;
 3 const int MaxStatckSize = 50; //定义栈的大小 
 4 class StackDemo
 5 {
 6 public:
 7     //析构造函数
 8     StackDemo(void);
 9     ~StackDemo(void);
10 
11     //压栈出栈操作
12     void Push( DataType item);
13     DataType Pop(void);
14     void ClearStack(void);
15 
16     //访问栈顶,返回栈顶当前下标
17     DataType Peek(void)const;
18 
19     //检测椎栈
20     bool isEmpty(void)const;
21     bool isFull(void)const;
22 
23 private:
24     DataType stacklist[MaxStatckSize];
25     int tos;//栈顶
26 };
View Code

实现 stackDemo.cpp

 1 #include "StackDemo.h"
 2 #include <iostream>
 3 using namespace std;
 4 StackDemo::StackDemo(void)
 5 {
 6     this->tos = -1;
 7 }
 8 StackDemo::~StackDemo(void)
 9 {
10     this->tos = -1;
11 }
12 void StackDemo::Push( DataType item)
13 {
14     //栈是否已满
15     if (!isFull())
16     {
17         tos++;
18         this->stacklist[tos] = item;
19 
20     }
21     else
22         cout << "Out of the Stack!" << endl;
23 }
24 
25 DataType StackDemo::Pop(void)
26 {
27     if (!isEmpty())
28     {
29         int ebp = tos;
30         tos --;
31         return stacklist[ebp];
32     }
33     else
34         return -1;
35 }
36 
37 DataType StackDemo::Peek(void)const
38 {
39     return tos;
40 }
41 
42 void StackDemo::ClearStack()
43 {
44     for (int i = tos; i >= 0; i--)
45         stacklist[i] = 0;
46     tos = -1;
47     cout << "Clear stack done!" << endl;
48 }
49 
50 bool StackDemo::isFull(void)const
51 {
52     return tos > MaxStatckSize ? true : false;
53 }
54 
55 bool StackDemo::isEmpty(void)const
56 {
57     return tos < 0 ? true : false;
58 }
View Code

main.cpp

 1 #include <iostream>
 2 #include "StackDemo.h"
 3 using namespace std;
 4  
 5 int main()
 6 {
 7     StackDemo *sd = new StackDemo();
 8     sd->Push(10);//压栈
 9     sd->Push(20);//压栈
10     sd->Push(30);//压栈
11     cout << "Stack TOP:" << sd->Peek() << endl;
12     for(int i=0;i<3;i++)
13     cout << "POP:" << sd->Pop() << endl;
14 
15     cout << "Stack TOP:" << sd->Peek() << endl;
16 
17     return 0;
18  
19 }
View Code

 

  

posted on 2016-10-03 10:54  IT小新手  阅读(394)  评论(0编辑  收藏  举报

导航