Home > Java > javaTutorial > body text

How can we implement stack using queue in Java?

王林
Release: 2023-08-25 17:05:11
forward
1438 people have browsed it

How can we implement stack using queue in Java?

A Stack (Stack) is a subclass of the Vector class, which represents a last-in-first-out (LIFO) object stack. The last element added to the top of the stack (In) can be the first element removed from the stack (Out).

Queue(Queue) class extends the Collection interface and supports insertion and deletion operations using first-in-first-out (FIFO). We can also use queues to implement stacks in the following program.

Example

import java.util.*;
public class StackFromQueueTest {
   Queue queue = new LinkedList();
<strong>   public void push(int value) {
</strong>      int queueSize = queue.size();
      queue.add(value);
      for (int i = 0; i < queueSize; i++) {
         queue.add(queue.remove());
      }
   }
<strong>   public void pop() {
</strong>      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);
   }
}
Copy after login

Output

<strong>[40, 30, 20, 10]
</strong>An element removed from a stack is: 40
<strong>[30, 20, 10]</strong>
Copy after login

The above is the detailed content of How can we implement stack using queue in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template