C++数据结构之Stack(栈)
2015-08-21 16:46
609 查看
stack,栈,是好比堆积木似的数据结构,从上之下堆积,取出时按“LIFO”-last int first out后进先出的规则。栈一般为线程所独有,也就是每个线程有其自有的栈,与heap堆一般为共有的不同(heap为进程所用,stack为线程所用?)。
stack主要有四种操作:empty判断栈是否为空;pop将栈顶的元素清除;top显示栈顶的元素(不是取走);push压栈,向栈内增加一个元素。
代码(在eclipse运行通过):
.h头文件
.cpp实现文件
main主程序测试文件:
代码中有一点重要的知识点,就是变量类型模板(不知道专业术语自己扯了这词)Stack_entry,这里的变量类型相当于一个模板,要能运行,必须先实例化这个模板,解决方法是用“typedef”(类型定义),比如:typedef char Stack_entry,这里就将Stack_entry实例化为char变量类型。
stack主要有四种操作:empty判断栈是否为空;pop将栈顶的元素清除;top显示栈顶的元素(不是取走);push压栈,向栈内增加一个元素。
代码(在eclipse运行通过):
.h头文件
#ifndef STACK #define STACK const int maxstack = 10; enum Error_code {overflow, underflow, success}; typedef int Stack_entry; class Stack { public: Stack(); bool empty()const; Error_code pop(); Error_code top(Stack_entry &item)const;// item作为取出值的载体 Error_code push(const Stack_entry &item);// item是放入的值 private: int count; Stack_entry entry[maxstack]; }; #endif /* STACK_ */
.cpp实现文件
#include "Stack.h" Stack::Stack() { count = 0; } bool Stack::empty()const { if(count == 0) return true; else return false; } Error_code Stack::pop() { if(empty()) return underflow; else count--; return success; } Error_code Stack::top(Stack_entry &item)const { if(count == 0) return underflow; else item = entry[count - 1]; return success; } Error_code Stack::push(const Stack_entry &item) { if(count >= maxstack) return overflow; else entry[count++] = item; // firstly make entry[count] = item,later count + 1 return success; }
main主程序测试文件:
#include "Stack.h" #include <cstdio> // or: #include "stdio.h" //using int main() { Stack mystack; mystack.push(2); int a; mystack.top(a); printf("%s %d","LvLang",a); return 0; }
代码中有一点重要的知识点,就是变量类型模板(不知道专业术语自己扯了这词)Stack_entry,这里的变量类型相当于一个模板,要能运行,必须先实例化这个模板,解决方法是用“typedef”(类型定义),比如:typedef char Stack_entry,这里就将Stack_entry实例化为char变量类型。
相关文章推荐
- 2015 Multi-University Training Contest 10 (hdu 5406-5416)数据结构+dp+矩阵快速幂+bitset优化拓扑排序+(dp&树状数组)
- 【数据结构与算法】——排序算法篇
- 【数据结构】线段树(interval tree)
- Python数据结构:映射(map)——字典
- 数据结构总结
- 数据结构笔记(郝斌主讲)(2015-11-26 22:16:36更新完毕)
- 【模拟+数据结构】UVA 11995 I Can Guess the Data Structure!
- 数据结构概念
- PAT《数据结构学习与实验指导》实验项目集 2-07. 素因子分解(20) C语言
- 【c++版数据结构】之单链表的实现(带头结点以及尾节点)
- 数据结构之AVL树
- 常见数据结构list template
- 在严蔚敏《数据结构(C语言版)》中,不能用动态分配的一维数组来实现循环队列
- 数据结构学习笔记之线性结构栈
- 数据结构List
- 本人对数据结构的理解,希望对大家有所帮助
- 数据结构-红黑树(Red-Black Tree)的C++实现模板
- 数据结构与算法之堆与堆排序
- 算法导论——(4)有序统计树(OrderStatisticTree,以红黑树为基本数据结构)
- C源码@数据结构与算法->Hashing