数据结构-简单栈的实现
来源:互联网 发布:vnc mac 连windows 编辑:程序博客网 时间:2024/05/20 21:48
简单的栈的实现,栈元素为类型为int,利用一个数组实现,使用时,构造栈有两种方式,一种为不指定栈的大小,默认原始大小为4,当元素超过当前大小时,则栈大小增长一倍,另一种为指定栈的大小,超过指定大小时抛出异常。栈的操作有:push(int value) 压栈int pop() 弹栈int peek() 查看栈顶boolean isEmpty() 判断栈是否为空boolean isFull() 判断是否已满,若为自动增长模式,即判断是否已达到当前栈的大小的值public int getSize() 获取栈的大小/** * Created by logaxy on 2017/1/3. */public class MyStack { private boolean actoIncrement = true;//栈是否自增长,当指定大小时为否 private static int INITIALSIZE = 4;//不指定栈大小时的初始化大小 private int array[];//栈以一个数组实现 private int top; MyStack() { array = new int[INITIALSIZE]; top = -1; } MyStack(int maxSize) { actoIncrement=false; if (maxSize < 0 || maxSize == 0) throw new IllegalArgumentException(); array = new int[maxSize]; top = -1; } void push(int value) { if (isFull()) { if (actoIncrement) { int[] temp = array; array = new int[2 * array.length]; System.arraycopy(temp, 0, array, 0, temp.length); } else { throw new IndexOutOfBoundsException(); } } array[++top] = value; } int pop() { if (isEmpty()) throw new IndexOutOfBoundsException(); return array[top--]; } int peek() { if (isEmpty()) throw new IndexOutOfBoundsException(); return array[top]; } boolean isEmpty() { return (top == -1); } boolean isFull() { return !(top < array.length - 1); } public int getSize() { return array.length; }}
测试程序:public class Main { public static void main(String[] args) { testStack(); } public static void testStack(){ MyStack myStack=new MyStack(); myStack.push(1); myStack.push(2); myStack.push(3); myStack.push(4); System.out.println("Top Is: "+myStack.peek()); System.out.println("Size IS:"+myStack.getSize()); System.out.println("Is Full: "+myStack.isFull()); myStack.push(5); myStack.push(6); System.out.println("Top Is: "+myStack.peek()); System.out.println("Size IS:"+myStack.getSize()); System.out.println("Is Full: "+myStack.isFull()); System.out.println(myStack.pop()); System.out.println(myStack.pop()); System.out.println(myStack.pop()); System.out.println(myStack.pop()); System.out.println(myStack.pop()); System.out.println(myStack.pop()); System.out.println("Is Empty:"+myStack.isEmpty()); System.out.println("Size IS:"+myStack.getSize()); }}
测试结果:
Top Is: 4
Size IS:4
Is Full: true
Top Is: 6
Size IS:8
Is Full: false
6
5
4
3
2
1
Is Empty:true
Size IS:8
0 0
- 数据结构-简单栈的实现
- 简单数据结构的实现之顺序栈
- 简单数据结构的实现之链栈
- 简单数据结构----链栈的C++实现
- 数据结构之栈的简单实现
- [数据结构]栈的C语言简单实现
- 数据结构栈C++简单实现
- 简单数据结构---数组实现栈
- 数据结构之栈的简单实例c++实现
- 数据结构C语言之栈的简单实现
- 【自己动手写数据结构】 -- 简单顺序栈的实现
- 算法与数据结构基础5:C++栈的简单实现
- 数据结构之简单四则运算表达式求值8-(栈的实现)
- 【数据结构与算法】(三) c 语言栈的简单实现
- 简单线性数据结构:栈和队列的实现
- Java -- 栈、队列等数据结构的简单链表实现
- C#数据结构单链表的简单实现
- 简单数据结构的实现之链队列
- Android文件解压工具类
- java自定义注解
- poj 3384 Feng Shui (半平面交)
- git-回退单个文件 到指定的版本
- 编程一小时
- 数据结构-简单栈的实现
- (HDU 5926)Mr. Frog’s Game 水题 <2016CCPC东北地区大学生程序设计竞赛 - 重现赛 >
- 2.Eclipse版本android 65535解决方案(原理等同android studio现在的分包方式)
- Android TextView自动换行文字排版参差不齐的原因
- Fragment和ViewPager的简单使用
- Swift语言一览
- MB21,MB_RESERVATION_BADI无法检查预留单所有项次
- 虽然很简单,但都是一些基础的东西,人非圣人,温故而知新.
- NET将关于多线程的功能