Queues: A Tale of Two Stacks

  • + 0 comments

    javascript with customized Queue

    class Queue {
      constructor() {
        this.inbox = []
        this.outbox = []
      }
    
      put(element) {
        this.inbox.push(element)
      }
    
      pop() {
        if (this.outbox.length == 0) {
          while (this.inbox.length) this.outbox.push(this.inbox.pop())
        }
        return this.outbox.pop()
      }
    
      peek() {
        if (this.outbox.length == 0) {
          while (this.inbox.length) this.outbox.push(this.inbox.pop())
        }
        return this.outbox[this.outbox.length - 1]
      }
    }
    
    function processData(input) {
      let lines = input.split('\n').slice(1)
      let queue = new Queue()
    
      for (let i = 0; i < lines.length; i++) {
        let [op, n] = lines[i].split(' ')
        switch (op) {
          case '1': queue.put(n); break
          case '2': queue.pop(); break
          case '3': console.log(queue.peek())
        }
      }
    }