Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active May 28, 2017 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/2edb7e5d73b9e085ba87c41566bfef07 to your computer and use it in GitHub Desktop.
Save anil477/2edb7e5d73b9e085ba87c41566bfef07 to your computer and use it in GitHub Desktop.
Implement stack using single queue
// The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.
// The remove() and poll() methods remove and return the head of the queue. Exactly which element is removed from the queue is a function of the queue's ordering policy, which differs from implementation to implementation. The remove() and poll() methods differ only in their behavior when the queue is empty: the remove() method throws an exception, while the poll() method returns null. NoSuchElementException is thrown by remove() if we try to remove element from an empty queue.
// The element() and peek() methods return, but do not remove, the head of the queue.
// isEmpty() to check if queue is empty. It returns boolean.
import java.util.LinkedList;
import java.util.Queue;
class StackOneQueue{
Queue<Integer> queue = new LinkedList<Integer>();
public void push(int data) {
queue.add(data);
System.out.println("Element Added : " + data);
int size = queue.size();
while (size > 1) {
queue.add(queue.remove());
size--;
}
}
public void pop() {
if(queue.isEmpty()){
System.out.println("Empty Queue");
}else{
System.out.println("Element Popped : " + queue.remove());
}
}
public void peek() {
System.out.println("Element on top: " + queue.element());
}
}
class StackUsingQueueApp {
public static void main(String[] args) {
StackOneQueue obj = new StackOneQueue();
obj.push(10);
obj.push(20);
obj.push(30);
obj.push(40);
obj.peek();
obj.pop();
obj.pop();
obj.pop();
obj.peek();
obj.push(50);
obj.push(60);
obj.peek();
obj.pop();
obj.pop();
obj.pop();
obj.pop();
obj.pop();
obj.pop();
obj.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment