用 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+ 瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告