STACK ADT
栈是限制插入和删除只能在一个位置上进行的表,该位置是表的末端,栈的顶。
对栈的基本操作有进战和出栈。栈有一个特性是先进后出。
由于栈是表的一种方式,所以任意实现表的方法都可以实现栈。
栈的链表实现
使用单链表,在表的顶端进行插入删除。
public class MyStack<AnyType> {
Node<AnyType> Bottom,beBottom;
int length;
public MyStack(){
doClear();
}
public void clear(){doClear();}
public void doClear(){
Bottom=new Node<>(null,null); //初始化栈底
length=0;
}
public int size(){return length;}
public Node<AnyType> getNode(int idx){ //根据位置获得节点,但一般都是栈顶
Node<AnyType> node=Bottom;
for (int i = 0; i < idx; i++)
node= node.behind;
return node;
}
public void put(AnyType data){put(size(),data);} //给用户提供 栈顶放入元素
public void put(int idx,AnyType data){putBehind(getNode(idx),data);}
public void putBehind(Node<AnyType> node,AnyType data){
Node<AnyType> newN=new Node<>(null,data);
node.behind=newN;
length++;
}
public AnyType push(){return push(size()-1);}//弹出栈顶元素
private AnyType push(int idx) {
if(idx<0)
throw new IndexOutOfBoundsException();
return pushTop(getNode(idx));
}//获得栈顶下一个元素
private AnyType pushTop(Node<AnyType> node) {
Node<AnyType> newN=node.behind;
node.behind=null;
length--;
return newN.data;
}
private static class Node<AnyType>{
AnyType data;
Node<AnyType> behind;
public Node(Node<AnyType> behind,AnyType data){
this.data=data;
this.behind=behind;
}
}
测试
public class Test {
public static void main(String[] args) {
MyStack<Integer> list1=new MyStack<>();
list1.put(1);
list1.put(2);
list1.put(3);
while (list1.size()!=0)
System.out.println(""+list1.push());
}
}
数组实现
第二种方法是数组实现,比较简单 不做提供。