Implement Queue Using two Stacks – JavaScript algorithm

javascript queue and stack implementation

Implement Queue Using two Stacks – JavaScript algorithm

Using stack data structure to implement queue in javascript

This is one way of implementing of the stack to be reused as queue using two stacks.

You may complain you are abusing the memory. But we are not copying the data on both stacks we are using the stacks for switching values only


            class Queue {
                constructor() {
                    this.inputStack = [];
                    this.outputStack = [];
                }

                enqueue(item) {
                    this.inputStack.push(item);
                }

                dequeue(item) {
                    this.outputStack = [];
                    if (this.inputStack.length > 0) {
                        while (this.inputStack.length > 0) {
                            this.outputStack.push(this.inputStack.pop());
                        }
                    }
                    if (this.outputStack.length > 0) {
                        console.log(this.outputStack.pop());
                        this.inputStack = [];
                        while (this.outputStack.length > 0) {
                            this.inputStack.push(this.outputStack.pop());
                        }
                    }
                }

                listIn() {
                    let i=0;
                    while(i < this.inputStack.length) {
                        console.log(this.inputStack[i]);
                        i++;
                    }
                }
                listOut() {
                    let i=0;
                    while(i < this.outputStack.length) {
                        console.log(this.outputStack[i]);
                        i++;
                    }
                }
            }

*There is part left out for improvement and refactoring. But, can you see a way to use only one while rather than two whiles and make it a bit efficient?

Check if Function Exists in Javascript

Java solution for checking anagram strings – tell if phrases are anagrams

Check if two strings are anagrams or not

Find K Complementary numbers from array Java implementation

how to get user input and process it in nodejs tutorial

how to display html files from node js example tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*