import java.util.LinkedList;
public class MyStack {
private LinkedList ll=new LinkedList();
public void push(Object o)
{
ll.addFirst(o);
}
public Object pop()
{
if(ll.isEmpty())
{
System.out.println("栈为空,不能出栈!");
return null;
}
return ll.removeFirst();
}
public Object peek()
{
return ll.getFirst();
}
public boolean empty()
{
return ll.isEmpty();
}
public static void main(String []args)
{
MyStack ms=new MyStack();
ms.push("one");
ms.push("two");
ms.push("three");
System.out.println(ms.pop());
System.out.println(ms.peek());
System.out.println(ms.pop());
System.out.println(ms.empty());
}
}
输出结果为
three
two
two
false
使用LinkedList实现栈
本文介绍了一个简单的Java程序,该程序利用LinkedList实现栈的基本操作:压栈(push)、弹栈(pop)、查看栈顶元素(peek)及判断栈是否为空(empty)。通过具体实例展示了栈的运作过程。
1269

被折叠的 条评论
为什么被折叠?



