Created
June 8, 2018 16:06
-
-
Save jmcmaster/0f1321fc781e2f19322899a59af7e504 to your computer and use it in GitHub Desktop.
JS Data Structures - Linked List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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