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
原创粉丝点击