在程序的世界,栈的应用是相当广泛的。其后进先出的特性,我们可以应用到诸如计算、遍历、代码格式校对等各个方面。但是你知道栈的底层是怎么实现的吗?现在跟随本篇文章我们来一睹它的庐山真面目吧。
首先我们先定义Stack的接口如下:
1 package com.chen.arithmetic_test.stack_test; 2 3 /** 4 * Created by ChenMP on 2017/7/4. 5 */ 6 public interface Stack { 7 //入栈 8 public void push(Object obj) throws Exception; 9 //出栈 10 public Object pop() throws Exception; 11 //获得栈顶元素 12 public Object getTop() throws Exception; 13 //判断栈是否为空 14 public boolean isEmpty(); 15 }
接下来,我们看看它的实现类:
1 package com.chen.arithmetic_test.stack_test; 2 3 /** 4 * Created by ChenMP on 2017/7/4. 5 */ 6 public class SequenceStack implements Stack { 7 private Object[] stack; //底层数据结构设计为对象数组 8 private int top; //栈顶位置标记 9 private int maxSize; //最大长度 10 11 public SequenceStack() { 12 this.stack = new Object[10];// 默认栈的长度为10 13 this.top = 0; 14 this.maxSize = 10; 15 } 16 17 public SequenceStack(int maxSize) { 18 this.stack = new Object[maxSize];// 默认栈的长度为10 19 this.top = 0; 20 this.maxSize = maxSize; 21 } 22 23 @Override 24 public void push(Object obj) throws Exception { 25 if(top == maxSize) 26 throw new Exception("堆栈已满!"); 27 28 stack[top] = obj; //添加入栈顶位置 29 top++; //栈顶位置标记+1 30 } 31 32 @Override 33 public Object pop() throws Exception { 34 if (0 == top) 35 throw new Exception("堆栈为空!"); 36 37 Object returnObj = stack[top]; //获取栈顶位置数据对象 38 stack[top] = null; //将该位置置为null,避免内存泄漏 39 top--; //栈顶位置标记-1 40 return returnObj ; 41 } 42 43 @Override 44 public Object getTop() throws Exception { 45 if (0 == top) 46 throw new Exception("堆栈为空!"); 47 48 return stack[top-1]; 49 } 50 51 @Override 52 public boolean isEmpty() { 53 return top>0?false:true; 54 } 55 }
来测试我们实现的顺序栈吧!
1 package com.chen.arithmetic_test.stack_test; 2 3 import java.util.Scanner; 4 5 /** 6 * Created by ChenMP on 2017/7/4. 7 */ 8 public class TestStack { 9 public static void main(String[] args) throws Exception { 10 // TODO Auto-generated method stub 11 SequenceStack stack = new SequenceStack(10); 12 13 Scanner in = new Scanner(System.in); 14 int temp; 15 for(int i=0;i<10;i++) 16 { 17 System.out.println("请输入第"+(i+1)+"个整数:"); 18 temp = in.nextInt(); 19 stack.push(temp); 20 } 21 22 while(!stack.isEmpty()) 23 { 24 System.out.println(stack.pop()); 25 } 26 } 27 }
通过上面的代码,其实也可以很清晰的理解顺序栈的实现原理对不对?给自己点个赞~