棧通常是指後進先出(LIFO)的容器,有時棧也被稱爲疊加棧,因爲最後"壓入"棧元素的元素,總是第一個彈出"棧"。
LinkedList具有能夠直接實現棧所有功能的方法,因此可以直接將LinkedList作爲棧使用。但是,真正的棧更能把事情講清楚。
例如:
例如:
public class Stack<T>{
private LinkedList<T> storage = new LinkedList<T>();
public void push(T,v){storage.addFirst(v)}
public T peek(){return storage.getFirst()}
public T pop(){return storage.removeFirst()}
public boolean empty(){return storage.isEmpty}
public String toString(){ reutrn storage.toString}
}
這裏通過泛型,引入了在棧的類定義中最簡單的可行實例。push()接受的是T類型的對象,而peek()和pop()將返回T類型的對象。
peek()方法將提供棧頂元素,但是並不將其衝棧頂移除,而pop將移除並返回棧頂元素。例如:
import java.util.Stack;
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
for(String s : "my dog has fleas".split(""))
stack.push(s);
while(!stack.empty())
System.out.print(stack.pop());
}
輸出:
saelf sah god ym
另外,創建實例的時候,就需要完整指定包名,不然就可能與net.,mindview.util.Stack包中發生衝突。