Computer Science, asked by vijakshita, 7 months ago

Is it possible to implement multiple stacks in a Queue. If Yes, (i)Is there any limit on the number

of Stacks that can be implemented in a Queue.(ii) Implement two Stacks in a Queue.​

Answers

Answered by SDJM
35

Answer:

yes, it is possible to implement multiple stacks in a Queue.

Implementing two Stacks in a Queue.

(1) When calling the enqueue method, simply push the elements into the stack 1.

(2) If the dequeue method is called, push all the elements from stack 1 into stack 2, which reverses the order of the elements. Now pop from stack 2.

Code

// implement stacks using plain arrays with push and pop functions

var Stack1 = [];

var Stack2 = [];

// implement enqueue method by using only stacks

// and the push and pop functions

function Enqueue(element) {

Stack1.push(element);

}

// implement dequeue method by pushing all elements

// from stack 1 into stack 2, which reverses the order

// and then popping from stack 2

function Dequeue() {

if (Stack2.length === 0) {

if (Stack1.length === 0) { return 'Cannot dequeue because queue is empty'; }

while (Stack1.length > 0) {

var p = Stack1.pop();

Stack2.push(p);

}

}

return Stack2.pop();

}

Enqueue('a');

Enqueue('b');

Enqueue('c');

Dequeue();

Did it help you??? tell me by giving a like to the answer

Similar questions