首页 > 编程语言 > 详细

栈的C++数组实现

时间:2020-01-02 23:37:23      阅读:101      评论:0      收藏:0      [点我收藏+]

1
#include "pch.h" 2 #include <iostream> 3 #include <stdlib.h> 4 using namespace std; 5 6 #define EmptyTOS -1 7 #define MinStackSize 5 //限定栈的最小容量 8 #define INCREMENT 5 //容量不足时内存分配增量 9 10 struct StackRecord 11 { 12 int cap;//记录栈的容量 13 int topOfStack;//记录栈的顶端位置 14 int *array;//指向栈(数组)的指针 15 }; 16 typedef struct StackRecord* stack; 17 18 //创建一个空栈,自定义容量大小 19 stack create_empty_stack(int capacity) 20 { 21 if (capacity < MinStackSize) 22 cout << "请指定一个更大的栈" << endl; 23 else 24 { 25 stack S = (stack)malloc(sizeof(StackRecord)); 26 S->cap = capacity; 27 S->topOfStack = EmptyTOS; 28 S->array = (int*)malloc(sizeof(int)*capacity); 29 return S; 30 } 31 } 32 //判断一个栈是否为空栈 33 bool isempty(stack S) 34 { 35 return S->topOfStack == EmptyTOS; 36 } 37 //判断是否满栈 38 bool isfull(stack S) 39 { 40 return (S->topOfStack+1) == S->cap; 41 } 42 //目前栈的大小 43 int length_stack(stack S) 44 { 45 return S->topOfStack + 1; 46 } 47 //释放栈 48 void dispose_stack(stack S) 49 { 50 if (isempty(S)) 51 { 52 free(S->array); 53 free(S); 54 } 55 } 56 //进栈 57 void push_stack(stack S,int x) 58 { 59 if (isfull(S)) 60 { 61 int old_cap = S->cap; 62 S->array = (int*)realloc(S->array, sizeof(int)*(S->cap + INCREMENT));//分配新空间 63 if (S == NULL) exit(OVERFLOW); 64 S->cap = old_cap+INCREMENT; 65 S->array[++S->topOfStack] = x; 66 } 67 else 68 S->array[++S->topOfStack] = x; 69 70 } 71 //出栈 72 void pop_stack(stack S) 73 { 74 if (isempty(S)) 75 cout << "栈已空" << endl; 76 else 77 S->topOfStack--; 78 } 79 //将栈顶返回 80 int top(stack S) 81 { 82 if (isempty(S)) 83 cout << "栈已空" << endl; 84 else 85 return S->array[S->topOfStack]; 86 } 87 //将栈顶返回并出栈 88 int top_and_pop(stack S) 89 { 90 if (isempty(S)) 91 cout << "栈已空" << endl; 92 else 93 { 94 return S->array[S->topOfStack]; 95 S->topOfStack--; 96 } 97 } 98 int main() 99 { 100 stack S; 101 S=create_empty_stack(5);//创建一个容量为10的栈 102 if (isempty(S)) 103 cout << "这是一个空栈" << endl; 104 for (int i = 0; i < 5; i++) 105 push_stack(S, i); 106 if (isfull(S)) 107 cout << "栈已满" << endl; 108 push_stack(S, 5);//继续进栈 109 cout << length_stack(S) << endl;//目前栈的大小 110 cout << top_and_pop(S) << endl; 111 system("pause"); 112 return 0; 113 }
技术分享图片

栈的C++数组实现

原文:https://www.cnblogs.com/cs0915/p/12142440.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!