自定义Stack
2015-07-05 11:00
232 查看
某些情况下,不能使用STL,那么就需要自定义栈,实现如下:
1.模板方法实现方式
栈的主要实体是一个单链表,每次入栈把结点插入表头,每次出栈删除表头结点
2.模板类实现方式
栈的实体是一个预先分配好的数组,入栈是往数组里加入元素,index后移;出栈是取出index位置元素,index前移。另外由于是预先分配大小,出现不够用的情况,则自动增加一倍大小size。
1.模板方法实现方式
栈的主要实体是一个单链表,每次入栈把结点插入表头,每次出栈删除表头结点
/* * 自定义栈 */ template<class T> struct Stack { T node; Stack* next; }; template<class T> void initStack(Stack<T> **s) { *s = new Stack<T>(); (*s)->next = NULL; } template<class T> void push(Stack<T> *s, T t) { Stack<T> *n = new Stack<T>(); n->node = t; n->next = s->next; s->next = n; } template<class T> T pop(Stack<T> *s) { if (s->next != NULL) { Stack<T> *t = s->next; s->next = t->next; T ret = t->node; delete t; return ret; } return NULL; } template<class T> bool empty(Stack<T> *s) { if (s->next != NULL) { return false; } return true; }
2.模板类实现方式
栈的实体是一个预先分配好的数组,入栈是往数组里加入元素,index后移;出栈是取出index位置元素,index前移。另外由于是预先分配大小,出现不够用的情况,则自动增加一倍大小size。
template<class T> class Stack { public: Stack(){ data = new T[1]; capacity = 1; top = -1; } void push(T t) { if (top+1 == capacity) { capacity *= 2; T* n = new T[capacity]; if (n == NULL) { return; } for(int i=0; i<=top; ++i) { n[i] = data[i]; } data = n; } data[++top] = t; } T pop() { T ret = data[top]; --top; return ret; } bool empty() { if (top == -1) { return true; } return false; } public: T* data; int top; int capacity; };
相关文章推荐
- hadoop入门(hadoop安装-hdfs简单介绍)
- 访问者模式
- printf 对齐
- android事件系列-onTouch事件与手势操作
- 调用fork两次以避免僵死进程的产生
- 错误代码: 1045 Access denied for user 'skyusers'@'%' (using password: YES)
- 对Mini-stream Ripper缓冲区溢出漏洞的体会
- ##*/ %%.*
- 错误代码: 1045 Access denied for user 'skyusers'@'%' (using password: YES)
- 前n项和公式
- 派生类向基类类型转换的可访问性
- 简单的Hibernate初探
- 实现textarea限制输入字数
- inlineCallbacks: A New Way towards Asynchronous Programming
- 【Leetcode】Largest Rectangle in Histogram #84
- 《算法导论》— Chapter 6 堆排序
- D3D网格(二)
- oracle 中AND OR 命令
- 操作系统常见面试的一些基础知识整理
- 彻底弄懂css中单位px和em的区别(转)