Answer to Question #254882 in Java | JSP | JSF for Dharmveer Singh

Question #254882

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.


1
Expert's answer
2021-10-21T16:03:28-0400


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());
    }
    
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS