Skip to content

Instantly share code, notes, and snippets.

@vadimkorr
Last active March 10, 2018 19:40
Show Gist options
  • Select an option

  • Save vadimkorr/2cd08b74b7fa695b0a9bd7c1661481ac to your computer and use it in GitHub Desktop.

Select an option

Save vadimkorr/2cd08b74b7fa695b0a9bd7c1661481ac to your computer and use it in GitHub Desktop.
Implement Queue interface using linked list
// linked-list-as-queue
function queue() {
this.head = null;
}
queue.prototype.print = function() {
console.log('print');
let curr = this.head
while(curr) {
console.log(curr.val)
curr = curr.next
}
}
queue.prototype.push = function(val) {
console.log('push');
let curr = this.head;
if (!this.head) {
this.head = {
val: val,
next: null
}
} else {
while(curr.next) {
curr = curr.next;
}
curr.next = {
val: val,
next: null
}
}
}
queue.prototype.pull = function() {
console.log('pull');
let pulled;
if (!this.head) {
pulled = null;
} else {
pulled = this.head;
this.head = this.head.next;
}
return pulled;
}
let q = new queue();
q.push(5);
q.push(4);
q.push(3);
q.push(2);
q.push(1);
q.print();
q.pull();
q.print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment