栈的Java实现
1、实现栈用Stack类,此类是Vector类的子类;
1 import java.util.Stack; 2 3 public class Stacks { 4 static String[] months = {"Janunary","February","March","aprile","May","June","July","Aug","Sep", 5 "October","November"}; 6 public static void main(String[] args) { 7 Stack stk = new Stack(); 8 9 for(int i=0;i<months.length;i++) 10 stk.push(months[i] + " "); //压栈 11 12 System.out.println("stk = " + stk); 13 14 stk.addElement("The last line"); //栈顶元素 15 stk.addElement("The last line1"); 16 System.out.println("element 5 = " + stk.elementAt(11)); 17 System.out.println("popping element;"); 18 while(!stk.empty()) 19 System.out.println(stk.pop()); //出栈 20 } 21 }
输出结果为:
stk = [Janunary , February , March , aprile , May , June , July , Aug , Sep , October , November ]
element 5 = The last line
popping element;
The last line1
The last line
November
October
Sep
Aug
July
June
May
aprile
March
February
Janunary
2、Stack类的常用方法:
1)boolean empty() 测试栈是否为空
2) peek() 查看栈顶,但不删除
3)pop() 出栈,同时删除
4)push() 入栈
5)int search(Object obj) 查找