Home >Java >javaTutorial >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.
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); } }
<strong>[40, 30, 20, 10] </strong>An element removed from a stack is: 40 <strong>[30, 20, 10]</strong>
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!