顺序栈(数组实现)
2015-10-05 16:02
309 查看
上面代码实现了Stack的 isEmpty(),isFull(),clear(),push(),pop(),peek()方法。顺序栈,必须要同时检查下溢出(underflow)和上溢出(overflow)。
public class Stack { private int[] stack; private static final int defaultSize = 100; private int size; private int topIndex; public Stack() { setUp(defaultSize); } public Stack(int sz) { setUp(sz); } public void setUp(int sz) { size = sz; topIndex = 0; stack = new int[size]; } public boolean isEmpty() { return topIndex == 0; } public boolean isFull() { return topIndex == size; } public void clear() { topIndex = 0; } public void push(int x) throws Exception { if(isFull()) throw new Exception("overflow"); else stack[topIndex++] = x; } public int pop() throws Exception { if(isEmpty()) throw new Exception("underflow"); else return stack[--topIndex]; } public int peek() throws Exception { if(isEmpty()) throw new Exception("underflow"); else return stack[topIndex-1]; } }
相关文章推荐
- LINUX VIM快捷键
- swift2.0 - 渐来的美好(也许应该要收回我之前说的话了)
- java:代理测试
- GO 学习笔记 (二) for , if , switch
- Nginx中location配置[转]
- Longest Common Prefix
- 高斯消元 【模板】
- 信息系统项目管理师2015年9月28日作业
- Android:Material Design(一) 概述
- UITapGestureRecognizer 的用法
- 八皇后问题--递归和非递归
- 读万卷书
- StudentDao
- 搜索
- 堆(优先队列)优化dijkstra(邻接矩阵)
- 阅读科研文献心得分享(一)
- JDBC示例程序
- 银行业务调度系统
- SysManagerService
- Android Notification