栈的基本操作

栈是一种元素满足后进先出(LIFO)规则的线性表。一般来说,我们将表头称为栈底,表尾称为栈顶,栈的操作都是在栈顶进行的。

栈的基本操作如下:

 1 //栈的基本操作
 2 template <typename Type> class Stack{
 3 private:
 4     Type *elements;
 5     int max_size,top_index;
 6 public:
 7     Stack(int length_input){
 8         elements=new Type[length_input];
 9         max_size=length_input;
10         //top_index初始化为-1,top_index+1永远等于当前元素个数
11         top_index=-1;
12     }
13     ~Stack(){
14         delete[] elements;
15     }
16 
17     //入栈操作
18     bool push(const Type &element){
19         //判断栈是否已满
20         if(top_index+1>=max_size){
21             return false;
22         }
23         top_index++;
24         elements[top_index]=element;
25         return true;
26     }
27 
28     //出栈操作
29     bool pop(){
30         if(top_index<0){
31             return false;
32         }
33         top_index--;
34         return true;
35     }
36 
37     //返回栈顶元素
38     Type top(){
39         //当栈为空时停止程序
40         //注意要加#include <cassert>
41         assert(top_index>=0);
42         return elements[top_index];
43     }
44 
45     //判断栈是否为空
46     bool empty() {
47         return top_index < 0;
48     }
49 };

 

转载于:https://www.cnblogs.com/NoviScl/p/6996629.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值