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