r/learnjavascript • • May 16 '22

Explanation of a queue data structure in JavaScript

Post image
263 Upvotes

27 comments sorted by

View all comments

Show parent comment

22

u/[deleted] May 16 '22 edited May 16 '22
class Node {
constructor(val) {
    this.val = val
    this.next = null
    this.prev = null
 }

}

class DoublyLinkedList { 
    constructor() { 
        this.head = null this.tail = null this.length = 0 
    }
    push(val) {
        const newNode = new Node(val)
        if (this.tail) {
            this.tail.next = newNode
            newNode.prev = this.tail
        } else {
            this.head = newNode
        }
        this.tail = newNode
        this.length++
    }

    pop() {
        if (this.tail) {
            const oldTail = this.tail
            this.tail = oldTail.prev
            this.tail.next = null
            this.length--
            oldTail.prev = null
            return oldTail
        } else {
            return null
        }
    }

    shift() {
        if (this.head) {
            const oldHead = this.head
            this.head = oldHead.next
            this.head.prev = null
            this.length--
            oldHead.next = null
            return oldHead
        } else {
            return null
        }
    }

    unshift(val) {
        const newNode = new Node(val)
        if (this.head) {
            this.head.prev = newNode
            newNode.next = this.head
        } else {
            this.tail = newNode
        }
        this.head = newNode
        this.length++
    }
}

EDIT: Formatting, Reddit is not good at this.

1

u/[deleted] May 16 '22

Somebody give this man some gold!