Stack Implementation using a Single Queue:
To implement Stack using single Queue, We have to push element in this way that last pused element should be ready to pop.
So after Push new element into queue we need to remove and push size-1 elements every time while adding new elements.
See the below image to get clarity.
As we can see in above image.
Push(1)
Push(2)
Push(3)
So As per Stack Operation pop order should be 3, 2 and then 1. which we have achieved in above figure.
Code for Push operation
package com.javaiq.in;
import java.util.LinkedList;
import java.util.Queue;
public class StackImplUsingSingleQueue {
Queue<Integer> q = new LinkedList<>();
void push(int x) {
// Add new element
q.add(x);
// remove and re-add size-1 elements
for (int i = 0; i < q.size() - 1; i++) {
q.add(q.remove());
}
}
int pop() {
return q.remove();
}
int top() {
return q.peek();
}
int size() {
return q.size();
}
}
Related Tutorial
No comments:
Post a Comment