Given two stacks with their standard operations (pop, push, isEmpty, size), implement a queue with its standard operations (enqueue, dequeue, isEmpty, size).
There should be two versions of the solution.
Version A: The queue should be efficient when enqueuing an item; and Version B: The queue should be efficient when dequeuing an item.
package queue;
import java.util.*;
import java.util.Queue;Â
public class QueueFromStack{
  Queue<Integer> queue1 = new LinkedList<Integer>();
  Queue<Integer> queue2 = new LinkedList<Integer>();
  public int pop() {
    if (queue1.peek() == null) {
      System.out.println("Underflow");
      int i = 0;
      return i;
    } else {
      int pop = queue1.remove();
      return pop;
    }
  }
  public void push(int data) {
    if (queue1.peek() == null) {
      queue1.add(data);
    } else {
      for (int i = queue1.size(); i > 0; i--) {
        queue2.add(queue1.remove());
      }
      queue1.add(data);
      for (int j = queue2.size(); j > 0; j--) {
        queue1.add(queue2.remove());
      }
    }
  }
  public static void main(String[] args) {
     QueueFromStack node = new QueueFromStack();
   Â
    node.push(1);
    node.push(2);
    node.push(3);
    node.push(4);
    node.push(5);
    node.push(6);
    node.push(7);
    node.push(8);
    node.push(9);
    node.push(10);
    Â
    System.out.println("1st = " + node.pop());
    System.out.println("2nd = " + node.pop());
    System.out.println("3rd = " + node.pop());
    System.out.println("4th = " + node.pop());
    System.out.println("5th = " + node.pop());
    System.out.println("6th = " + node.pop());
    System.out.println("7th = " + node.pop());
    System.out.println("8th = " + node.pop());
    System.out.println("9th = " + node.pop());
    System.out.println("10th= " + node.pop());
  }
  Â
}
Comments
Leave a comment