用 Java 从 LinkedList 那里实现一个堆栈
可以通过将 LinkedList 管理为堆栈来使用 LinkedList 实现堆栈。为此,可以使用包含部分 Stack 方法(例如 push()、top()、pop() 等)的类 Stack。
下面给出一个演示此示例的程序 −
示例
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
现在让我们了解以上程序。
一个类 Stack 包含部分 Stack 方法(例如 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() 方法中,创建了类的对象 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());
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP