定义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();
}
定义Stack实现类
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++;
}
@Override
public Object pop() throws Exception {
if (0 == top)
throw new Exception("堆栈为空!");
Object returnObj = stack[top];
stack[top] = null;
top--;
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());
}
}
}