Skip to content

Instantly share code, notes, and snippets.

@marijer
Last active December 28, 2015 06:39
Show Gist options
  • Save marijer/7458394 to your computer and use it in GitHub Desktop.
Save marijer/7458394 to your computer and use it in GitHub Desktop.
// HOMEWORK WEEK 3 - Day 2
var LinkedList = function() {
this.head = null;
this.tail = null;
this.numItems = 0;
}
var newNode = function( data ) {
this.data = data;
this.next = null;
}
LinkedList.prototype.enqueue = function( data ) {
var node = new newNode(data);
if (this.head === null) {
this.head = node;
this.next = null;
} else {
this.tail.next = node;
}
this.numItems++;
this.tail = node;
}
LinkedList.prototype.dequeue = function( callback ) {
if ( this.numItems === 0 ) {
return callback ("no items in the list");
} else {
var popped = this.head;
this.head.next = this.head;
this.numItems--;
return callback (null, popped);
}
}
LinkedList.prototype.size = function() {
return this.numItems;
}
var test = function( err, el ) {
if( err ) {
console.log (err);
} else {
console.log ( el.data + ' has been removed;')
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TEST CODE
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// creates a new linked list
var ll = new LinkedList();
ll.dequeue(test);
ll.enqueue ("1");
ll.enqueue ("2");
ll.enqueue ("3");
console.log (ll.head);
ll.dequeue(test);
console.log ( ll.size() );
/*
Implement a Queue data structure as a JavaScript object that contains the following methods:
enqueue(data) - Adds a new data element to the queue
The parameter, data, should be the element to add.
dequeue(callback) - Removes the next item from the queue
The parameter to dequeue is a callback function that should expect two parameters - err and value. The callback's first param, err, is set to null if the queue operation was successful or "Empty" if the queue is currently empty. The callback's second parameter, value, is the value removed from the queue.
size() - Return the number of elements current in the queue
As with your stack implementation, you are not allowed to use the JavaScript array or any 3rd party libraries. Place your solution in a file called queue.js and upload it as submission of your assignment.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment