从Java中的LinkedList实现堆栈
通过将LinkedList作为堆栈进行管理,可以使用LinkedList实现堆栈。这是通过使用一类堆栈包含一些的堆栈的方法,例如完成push(),top(),pop()等。
演示此的程序如下所示-
示例
import java.util.LinkedList;
class Stack {
private LinkedList l = new LinkedList();
public void push(Object obj) {
l.addFirst(obj);
}
public Object top() {
return l.getFirst();
}
public Object pop() {
return l.removeFirst();
}
}
public class Demo {
public static void main(String[] args) {
Stack s = new Stack();
s.push(5);
s.push(1);
s.push(3);
s.push(9);
s.push(7);
System.out.println("The top element of the stack is: " + s.top());
System.out.println("The stack element that is popped is: " + s.pop());
System.out.println("The stack element that is popped is: " + s.pop());
System.out.println("The top element of the stack is: " + s.top());
}
}输出结果
The top element of the stack is: 7 The stack element that is popped is: 7 The stack element that is popped is: 9 The top element of the stack is: 3
现在让我们了解上面的程序。
一类堆栈创建包含一些的堆栈的方法,例如push(),top(),pop()等等的代码段这表明这是如下-
class Stack {
private LinkedList l = new LinkedList();
public void push(Object obj) {
l.addFirst(obj);
}
public Object top() {
return l.getFirst();
}
public Object pop() {
return l.removeFirst();
}
}在该方法中main(),将创建Stack类的对象s。然后,将其用于将元素推入堆栈,显示堆栈中的顶部元素和弹出元素。演示这的代码片段如下-
public static void main(String[] args) {
Stack s = new Stack();
s.push(5);
s.push(1);
s.push(3);
s.push(9);
s.push(7);
System.out.println("The top element of the stack is: " + s.top());
System.out.println("The stack element that is popped is: " + s.pop());
System.out.println("The stack element that is popped is: " + s.pop());
System.out.println("The top element of the stack is: " + s.top());
}热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短