Skip to content

Instantly share code, notes, and snippets.

@jmcmaster
Created June 8, 2018 16:06
Show Gist options
  • Save jmcmaster/0f1321fc781e2f19322899a59af7e504 to your computer and use it in GitHub Desktop.
Save jmcmaster/0f1321fc781e2f19322899a59af7e504 to your computer and use it in GitHub Desktop.
JS Data Structures - Linked List
function Node(data) {
this.data = data;
this.next = null;
}
function LinkedList() {
this.head = null;
}
LinkedList.prototype.addNode = function(node) {
if (this.head === null) {
this.head = node;
} else {
var current = this.head;
while (current.next != null) {
current = current.next;
}
current.next = node;
}
};
LinkedList.prototype.countNodes = function() {
var count = 0;
var current = this.head;
while (current != null) {
count += 1;
if (current.next != null) {
current = current.next;
} else {
current = null;
}
}
return count;
};
var list = new LinkedList();
list.addNode(new Node(6));
list.addNode(new Node(3));
list.addNode(new Node(33));
console.log('This is the head: ', list.head);
console.log('How many nodes? ' + list.countNodes());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment