Implement Stack using Two Queues

后端 未结 23 806
感情败类
感情败类 2020-11-28 17:05

A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack. The question...

Given two queues with their sta

23条回答
  •  清歌不尽
    2020-11-28 17:48

    Here's one more solution:

    for PUSH : -Add first element in queue 1. -When adding second element and so on, Enqueue the element in queue 2 first and then copy all the element from queue 1 to queue2. -for POP just dequeue the element from the queue from you inserted the last element.

    So,

    public void push(int data){
    if (queue1.isEmpty()){
        queue1.enqueue(data);
    }  else {
    queue2.enqueue(data);
    while(!queue1.isEmpty())
    Queue2.enqueue(queue1.dequeue());
    //EXCHANGE THE NAMES OF QUEUE 1 and QUEUE2
    

    } }

    public int pop(){
    int popItem=queue2.dequeue();
    return popItem;
    }'
    

    There is one problem, I am not able to figure out, how to rename the queues???

提交回复
热议问题