如何在 Java 中使用队列实现堆栈?

javaobject oriented programmingprogramming更新于 2024/5/10 15:23:00

StackVector 类的子类,它表示对象后进先出 (LIFO) 堆栈。添加到堆栈顶部的最后一个元素 (In) 可以是第一个从堆栈中删除的元素 (Out)。

Queue 类扩展了 Collection 接口,它支持使用先进先出 (FIFO)插入删除操作。我们还可以在以下程序中使用队列实现堆栈。

示例

import java.util.*;
public class StackFromQueueTest {
   Queue queue = new LinkedList();
   public void push(int value) {      int queueSize = queue.size();
      queue.add(value);
      for (int i = 0; i < queueSize; i++) {
         queue.add(queue.remove());
      }
   }
   public void pop() {      System.out.println("An element removed from a stack is: " + queue.remove());
   }
   public static void main(String[] args) {
      StackFromQueueTest test = new StackFromQueueTest();
      test.push(10);
      test.push(20);
      test.push(30);
      test.push(40);
      System.out.println(test.queue);
      test.pop();
      System.out.println(test.queue);
   }
}

输出

[40, 30, 20, 10]An element removed from a stack is: 40
[30, 20, 10]

相关文章