Last active
January 9, 2019 07:08
-
-
Save IAMIronmanSam/50560d9008b79033e7e9d58200f38b9e to your computer and use it in GitHub Desktop.
Simple implementation on linked list in JS
This file contains 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 SinglyList() { | |
this._length = 0; | |
this.head = null; | |
} | |
SinglyList.prototype.add = function(value){ | |
var node = new Node(value); | |
var currentNode = this.head; | |
// 1st use-case: an empty list | |
if(!currentNode){ | |
this.head = node; | |
this._length ++; | |
return node; | |
} | |
// 2nd use-case: a non-empty list | |
while(currentNode.next){ | |
currentNode = currentNode.next; | |
} | |
currentNode.next = node; | |
this._length ++; | |
return node; | |
} | |
SinglyList.prototype.searchNodeAt = function(position) { | |
var currentNode = this.head, | |
length = this._length, | |
count = 1, | |
message = {failure: 'Failure: non-existent node in this list.'}; | |
// 1st use-case: an invalid position | |
if (length === 0 || position < 1 || position > length) { | |
throw new Error(message.failure); | |
} | |
// 2nd use-case: a valid position | |
while (count < position) { | |
currentNode = currentNode.next; | |
count++; | |
} | |
return currentNode; | |
}; | |
SinglyList.prototype.searchNodeByValue = function(data) { | |
var currentNode = this.head; | |
var count = 0; | |
while (currentNode.data) { | |
if(currentNode.data === data){ | |
return currentNode; | |
} | |
currentNode = currentNode.next; | |
count++; | |
} | |
}; | |
var linkedList = new SinglyList(); | |
linkedList.add(10); | |
linkedList.add(20); | |
console.log(linkedList) | |
var searchByIndex = linkedList.searchNodeAt(1); | |
var searchByValue = linkedList.searchNodeByValue(20); | |
console.log(searchByIndex); | |
console.log(searchByValue); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment