Queue using Two Stacks

  • + 0 comments
    function processData(input) {
      // Define a queue
      class Fifo {
        constructor() {
          this.stackEnqueue = [];
          this.stackDequeue = [];
        }
    
        enqueue(x) {
          this.stackEnqueue.push(x);
        }
    
        transfer() {
          while (this.stackEnqueue.length > 0) {
            this.stackDequeue.push(this.stackEnqueue.pop());
          }
        }
        dequeue() {
          if (this.stackDequeue.length === 0) {
            this.transfer();
          }
          this.stackDequeue.pop();
        }
        peek() {
          if (this.stackDequeue.length === 0) {
            this.transfer();
          }
          if (this.stackDequeue.length === 0) {
            return null;
          } else {
            return this.stackDequeue[this.stackDequeue.length - 1];
          }
        }
      }
    
      let q = new Fifo();
    
      // Parse input
    
      const inputs = input.split('\n');
    
      for (let i = 1; i <= Number(inputs[0]); i++) {
        const element = inputs[i];
        const inputArray = element.split(' ');
    
        const action = Number(inputArray.shift());
        const value = Number(inputArray.join(''));
    
        switch (action) {
          case 1:
            q.enqueue(value);
            break;
    
          case 2:
            q.dequeue();
            break;
    
          case 3:
            console.log(q.peek());
            break;
    
          default:
            console.log('DEFAULT REACHED');
            console.log('Unexpected action', action, 'With Value', value);
    
            break;
        }
      }
    }