Skip to content

Instantly share code, notes, and snippets.

@noman-land
Created December 21, 2017 06:13
Show Gist options
  • Save noman-land/24c8c0dbb426c6af10cb9c6689a8741d to your computer and use it in GitHub Desktop.
Save noman-land/24c8c0dbb426c6af10cb9c6689a8741d to your computer and use it in GitHub Desktop.
Linked List implementation of a queue
function LinkNode(value, prev = null, next = null) {
this.value = value;
this.prev = prev;
this.next = next;
}
function Queue() {
this.head = null;
this.tail = null;
this.isEmpty = function isEmpty() {
return this.head === null;
};
this.push = function push(value) {
const newNode = new LinkNode(value);
if (this.isEmpty()) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.next = this.head;
this.head.prev = newNode;
this.head = newNode;
}
return this.head;
};
this.pop = function pop() {
if (this.isEmpty()) {
return null;
}
const tailNode = this.tail;
if (tailNode === this.head) {
this.head = this.tail = null;
return tailNode.value;
}
this.tail = tailNode.prev;
tailNode.prev = null;
this.tail.next = null;
return tailNode.value;
};
}
const q = new Queue();
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
q.pop();
q.pop();
q.pop();
q.pop();
q.pop();
q.pop();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment