Queues: A Tale of Two Stacks

  • + 0 comments

    JavaScript

    class Queue {
      constructor() {
        this.result = [];
      }
      enque(value) {
        this.result.push(value);
      }
    
      dequeue() {
        if (this.result.length != 0) {
          this.result.shift();
        }
      }
    
      print() {
        if (this.result.length != 0) {
          console.log(this.result[0]);
        }
      }
    }
    function processData(input) {
      let inputArr = input.split("\n");
      let tab = new Queue();
      for (let i = 1; i < inputArr.length; i++) {
        switch (inputArr[i][0]) {
          case "1":
            let value = inputArr[i].slice(1).trim();
            tab.enque(value);
            break;
          case "2":
            tab.dequeue();
            break;
          case "3":
            tab.print();
            break;
        }
      }
    }