Implement a stack data structure using a single queue.
Note: A stack is a data structure that follows the LIFO (Last-In-First-Out) approach.
Solutions
Method 1: Using single Queue
In order to implement Stack using a single queue, we need to make a simple change in the push() method. Other methods like pop(), top() and size() will remain the same.
While adding to a queue, elements are inserted in a FIFO manner, i.e., the element inserted last will come out last. This behaviour is just the opposite to a Stack LIFO implementation.
So our task is to make sure that the last added element comes out first.
We can achive this by using a for loop of size()-1 (0 to n-2), remove element from queue and again push back to the queue, hence the most recent element becomes the most former element and vice versa.
package com.cb.stack; | |
import java.util.LinkedList; | |
import java.util.Queue; | |
/* | |
* Stack using Queue | |
* Time: O(N) | |
* Space: O(N) | |
* */ | |
public class ST2_ImplementStackUsingSingleQueue { | |
private Queue<Integer> q = new LinkedList<>(); | |
public void push(int e) { | |
q.add(e); | |
// last becomes first | |
for (int i = 0; i < q.size() - 1; i++) | |
q.add(q.poll()); | |
} | |
public int pop() { | |
return q.poll(); | |
} | |
public int top() { | |
return q.peek(); | |
} | |
public int size() { | |
return q.size(); | |
} | |
} | |
class ST2Impl { | |
public static void main(String[] args) { | |
ST2_ImplementStackUsingSingleQueue stack = new ST2_ImplementStackUsingSingleQueue(); | |
stack.push(1); | |
stack.push(2); | |
stack.push(3); | |
System.out.println(stack.size()); | |
System.out.println(stack.top()); | |
System.out.println(stack.pop()); | |
System.out.println(stack.pop()); | |
stack.push(4); | |
stack.push(5); | |
} | |
} |
Complexity
The time complexity of this solution is O(N) and space complexity is O(N).