提供一个接口 

package com.mo.stack;

/**
* 这是栈的接口,抽象数据类型
*/
public interface Stack {
/**
* 入栈
*/
void push(Object obj) throws Exception;
/**
* 出栈
*/
Object pop() throws Exception;
/**
* 取出栈的元素
*/
Object getTop() throws Exception;
/**
* 栈是不是为空
*/
boolean isEmpty();
}



用数组实现的栈


package com.mo.stack;

public class SeqStack implements Stack {

private final static int defaultSize = 10;//默认创建的数组大小
private int top;//栈顶的元素的下标
private Object[] stack;//栈数组
private int maxStackSize;//数组的容量

public SeqStack() {
init(defaultSize);
}
public SeqStack(int size) {
init(size);
}
private void init(int size) {
stack = new Object[size];
top = 0;
maxStackSize = size;
}
public void push(Object obj) throws Exception {
if(top == maxStackSize) throw new Exception();
stack[top] = obj;
top++;
}
public Object pop() throws Exception {
if(top == 0) throw new Exception();
Object obj = stack[top - 1];
top--;
return obj;
}
public Object getTop() throws Exception {
if(top < 0) throw new Exception();
return stack[top - 1];
}
public boolean isEmpty() {
return top == 0;
}
public static void main(String[] args) throws Exception {
SeqStack seqStack = new SeqStack();
for(int i = 0; i < 10; i++) {
seqStack.push(i);
}
while(!seqStack.isEmpty()) {
System.out.print(seqStack.pop());
}
}
}



用链表实现的栈


package com.mo.stack;

import com.mo.linList.Node;

//链表实现的堆栈
public class LinStack implements Stack{

private Node head;//栈顶
private int size;//栈中的元素个数

public LinStack() {
head = null;
size = 0;
}

public void push(Object obj) throws Exception {
Node node = new Node(obj,head);//把首节点放在新增的obj后面
head = node;//设为当前节点
size++;
}

public Object pop() throws Exception {
if(size == 0) throw new Exception();
Object oldHead = head.getData();//获取首节点的元素数据
head = (Node)head.getNext();//把链表的下一个Node设为当前节点
size--;
return oldHead;
}

public Object getTop() throws Exception {
if(size == 0) throw new Exception();
return head.getData();
}

public boolean isEmpty() {
return size == 0;
}

public static void main(String[] args) throws Exception {
LinStack linStack = new LinStack();
for(int i = 0; i < 10; i++) {
linStack.push(i+1);
}
while(!linStack.isEmpty()) {
System.out.print(linStack.pop());
}
}


}