code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

01 Queue Using Linked List

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */
const QueueNode = require('../models/list-node')

class Queue {
  constructor() {
    this.front = null
    this.tail = null
    this.size = 0
  }

  isEmpty() {
    return this.size === 0
  }

  enqueue(data) {
    let node = new QueueNode(data)
    if (this.isEmpty()) {
      this.front = node
      this.tail = node
    } else {
      this.tail.next = node
      this.tail = node
    }
    this.size += 1
  }

  dequeue() {
    if (this.front === null) {
      return null
    }
    let result = this.front.data
    if (this.front === this.tail) {
      this.front = null
      this.tail = null
    } else {
      this.front = this.front.next
    }
    this.size -= 1
    return result
  }
}

// let qq = new Queue()
// qq.enqueue("A")
// qq.enqueue("S")
// qq.enqueue("H")
// qq.enqueue("I")
// qq.enqueue("S")
// qq.enqueue("H")

// while(!qq.isEmpty()){
//   console.log(qq.dequeue())
// }

module.exports = Queue

Created 2019-12-01T03:42:47+05:18 · Edit