用 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());
}

更新于: 30-Jul-2019

3000+ 浏览

启动您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.