栈是在数据结构中比较常见的一种形式,栈是采用典型的先进后出的操作方式完成的。
栈是采用先进后出的数据存储方式,每一个栈都包含一个栈顶,每次出栈是将栈顶的数据取出

在java中使用Stack类进行栈的操作,Stack类是Vector的子类,Stack的定义如下
public class Stack<E>extends Vector<E>

事例
package com.qn.test;
import java.util.Stack;
public class StackTest {
public static void main(String[] args) {
Stack<String> s=new Stack<String>();
s.push("A");//入栈
s.push("B");//入栈
s.push("C");//入栈
s.push("D");//入栈
System.out.println(s.pop());//先进后出
System.out.println(s.pop());//先进后出
System.out.println(s.pop());//先进后出
System.out.println(s.pop());//先进后出
}
}
结果

如果栈中没有内容了,则无法继续出栈
如下
package com.qn.test;
import java.util.Stack;
public class StackTest {
public static void main(String[] args) {
Stack<String> s=new Stack<String>();
s.push("A");//入栈
s.push("B");//入栈
s.push("C");//入栈
s.push("D");//入栈
System.out.println(s.pop());//先进后出
System.out.println(s.pop());//先进后出
System.out.println(s.pop());//先进后出
System.out.println(s.pop());//先进后出
System.out.println(s.pop());//先进后出
}
}
会出下面的空栈异常
