栈也叫后进先出表,同样分为线性存储和链式存储两种不同的方式。
package org.stack.cn;
public interface StackADT {
/***
* 向栈顶插入一个元素
* @param obj 插入的元素
*/
void push(Object obj);
/**
* 栈顶删除一个元素
* @return
*/
Object pop();
/**
* 返回栈顶元素的值
* @return
*/
Object peek();
/***
* 判断是否为空栈 是-->true
* @return
*/
boolean isEmpty();
/***
* 清楚栈中的元素成为空栈
*/
void clear();
}
package org.stack.cn;
/**
* 栈的顺序存储结构操作实现
* @author Administrator
*
*/
public class SequenceSatck implements StackADT {
private final int maxSize=10;
private Object[] stackArray;
private int top;//定义数组中所保存的栈顶元素的下标位置
public SequenceSatck() {
// TODO Auto-generated constructor stub
top=-1; //栈的初始位置为空
stackArray=new Object[maxSize];
}
public SequenceSatck(int n){
if(n<=0){
System.out.println("s数组长度要大于0");
}
top=-1;
stackArray=new Object[n];
}
@Override
public void push(Object obj) {
// TODO Auto-generated method stub
if(top==stackArray.length-1){
Object[] p=new Object[top*2+2];
for(int i=0;i<top;i++){
p[i]=stackArray[i];//复制数组内容到新数组中
stackArray=p;
}
}
top++;
stackArray[top]=obj;
}
@Override
public Object pop() {
// TODO Auto-generated method stub
if(top==-1){
System.out.println("栈是空的");
return null;
}
top--;
return stackArray[top+1];
}
@Override
public Object peek() {
// TODO Auto-generated method stub
if(top==-1){
System.out.println("栈是空的,无法读取元素");
return null;
}
return stackArray[top];
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return top==-1;
}
@Override
public void clear() {
// TODO Auto-generated method stub
top=-1;
}
}
package org.stack.cn;
/***
* 栈的链式存储结构
* @author Administrator
*
*/
public class LinkStack implements StackADT {
private Node top; //定义top为栈顶指针的引用
private class Node{
private Object data;//数据域
private Node next; //指针域 存储下一个节点的引用
public Node(Node next){
this.next=next;
}
public Node(Object obj,Node next){
this.data=obj;
this.next=next;
}
}
public LinkStack() {
// TODO Auto-generated constructor stub
top=null;
}
@Override
public void push(Object obj) {
// TODO Auto-generated method stub
top=new Node(obj,top);
}
@Override
public Object pop() {
// TODO Auto-generated method stub
if(top==null){
System.out.println("栈是空的");
return null;
}
Object x=top.data;
top=top.next;
return x;
}
@Override
public Object peek() {
// TODO Auto-generated method stub
if(top==null){
System.out.println("栈是空的");
return null;
}
return top.data;
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return top==null;
}
@Override
public void clear() {
// TODO Auto-generated method stub
top=null;
}
}