LinkedList的方法能直接實現棧的功能,所以你完全可以不寫stack而直接使用LinkedList。
import java.util.LinkedList;
public class MyStack
{
private LinkedList list = new LinkedList();
public int StackLength()//返回棧的長度
{
return list.size();
}
public boolean StackEmpty()//判斷棧是否爲空
{
return list.isEmpty();
}
public void push(Object o)//進棧
{
list.addFirst(o);
}
public Object pop()//出棧
{
if(!list.isEmpty())
{
return list.remove();
}
return "棧內無元素";
}
public Object peek()//顯示棧頭元素
{
return list.getFirst();
}
public void clear()//清除棧
{
list.clear();
}
public static void main(String[] args)//棧MyStack測試
{
MyStack stack = new MyStack();
System.out.println(stack.StackEmpty());
stack.push("a");
stack.push("b");
stack.push("c");
stack.push("d");
stack.push("e");
stack.push("f");
System.out.println(stack.StackLength());
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.peek());
stack.clear();
stack.push("t");
stack.push("s");
System.out.println(stack.pop());
System.out.println(stack.StackLength());
System.out.println(stack.peek());
}
}
結果
6
f
f
e
d
s
1
t