frontend-challenges icon indicating copy to clipboard operation
frontend-challenges copied to clipboard

104 - Queue using Stack - javascript

Open jsartisan opened this issue 2 months ago • 0 comments

index.js

import { Stack } from "./stack";

class Queue {
  constructor() {
    this.inStack = new Stack();
    this.outStack = new Stack();
  }

  enqueue(element) {
    this.inStack.push(element);
  }

  _shiftStacks() {
    if (this.outStack.size() === 0) {
      while (this.inStack.size() > 0) {
        this.outStack.push(this.inStack.pop());
      }
    }
  }

  peek() {
    this._shiftStacks();
    return this.outStack.peek();
  }

  dequeue() {
    this._shiftStacks();
    return this.outStack.pop();
  }

  size() {
    return this.inStack.size() + this.outStack.size();
  }
}

export { Queue };

jsartisan avatar Sep 27 '25 04:09 jsartisan