C++数据结构之Stack(栈)
来源:互联网 发布:淘宝差评卖家会退款吗 编辑:程序博客网 时间:2024/06/06 20:19
stack,栈,是好比堆积木似的数据结构,从上之下堆积,取出时按“LIFO”-last int first out后进先出的规则。栈一般为线程所独有,也就是每个线程有其自有的栈,与heap堆一般为共有的不同(heap为进程所用,stack为线程所用?)。
stack主要有四种操作:empty判断栈是否为空;pop将栈顶的元素清除;top显示栈顶的元素(不是取走);push压栈,向栈内增加一个元素。
代码(在eclipse运行通过):
.h头文件
#ifndef STACK#define STACKconst 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;elsereturn false;}Error_code Stack::pop(){if(empty())return underflow;elsecount--;return success;}Error_code Stack::top(Stack_entry &item)const{if(count == 0)return underflow;elseitem = entry[count - 1];return success;}Error_code Stack::push(const Stack_entry &item){if(count >= maxstack)return overflow;elseentry[count++] = item;// firstly make entry[count] = item,later count + 1return success;}
main主程序测试文件:
#include "Stack.h"#include <cstdio> // or: #include "stdio.h"//usingint 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变量类型。
0 0
- 数据结构之栈stack
- C++数据结构之Stack(栈)
- 基本数据结构之栈(stack)
- Java 数据结构之 Stack(栈)
- JavaScript数据结构之--------栈(Stack)
- 栈(stack )数据结构
- C源码@数据结构与算法->栈Stack
- 数据结构之栈(stack)初步简单实现
- java数据结构之——Stack(栈)
- 数据结构之栈(附:Stack/Vector源码分析)
- 数据结构之 栈stack 模板类(数组描述方法)
- 数据结构之 栈stack 模板类(链表表示)
- 基本数据结构:栈(stack)
- 基本数据结构:栈(stack)
- 基本数据结构:栈(stack)
- C++数据结构之Linked Stack(链式栈)
- Java数据结构与算法之stack栈
- [Java数据结构]线性表之栈Stack
- 动态菜单----动态生成菜单和java反射机制的使用
- 微营销王萍分享如何让销量暴涨的7个方法
- tar命令的详细解释
- python numpy 把数据向量化
- jq 父级iframe 相关操作
- C++数据结构之Stack(栈)
- git基础之创建ssh公钥和密钥
- Fastboot线刷“复活”之刷机心得(一)——背景简介
- 品尝棉花糖之Nexus5线刷Android6.0攻略
- 【网络编程】之十三、ping程序实现
- MacBook下Android Studio使用SVN两个小问题
- iOS (在Xcode下载模拟器很慢解决方法)
- 获取控件的宽高的两种方法
- Service启动方式之startService