Interview Question to Make Queue using two stakes.

Please follow & like us :)

Stack Queue

You have given two stacks and you need to create Queue data Structure.

Now we know Stack data structure is “LIFO” access. LIFO = Last In First Out. That means in Stack data organizer you get last element first and first element last.

Read More About Data Structure and Algorithm

Whereas Queue is “FIFO” access. FIFO = Fist In Fist Out. That means in Queue we will get First Element First, Last Element Last, in order.

Coding Challenge Solution

Let’s Say you have one stack.

let stackOne = []

Now We have input numbers => 1, 2, 3, 4, 5, 6

Lets push all the numbers => 1, 2, 3, 4, 5, 6

Now if you pop from this Stack you will get 6, but in Queue we should get 1.

So If we take 6 and put in Stack2, it will be first element. So Order will be [6, 5, 4, 3, 2, 1]

And now we do have 1 as last element so we will get as first element from stack2 which we were expecting in Queue Data Organizer.

And now we can start writing actual code to solve this question.

let stack1 = [];
let stack2 = [];

const enQueue = (num) => {
  stack1.push(num);
}

const deQueue = () => {
  if (stack2.length === 0) {
    if (stack1.length === 0) return false;
    while (stack1.length > 0) {
      let p1 = stack1.pop();
      stack2.push(p1);
    }
  }
  console.log(stack2);
  return stack2.pop();
}

enQueue(4);
enQueue(5);
enQueue(6);
console.log(stack1);
console.log(deQueue());