Skip to content

Instantly share code, notes, and snippets.

@marcogbarcellos
Created February 8, 2017 03:52
Show Gist options
  • Save marcogbarcellos/e8a65f0b76c5cc649fad3cbe9b74030c to your computer and use it in GitHub Desktop.
Save marcogbarcellos/e8a65f0b76c5cc649fad3cbe9b74030c to your computer and use it in GitHub Desktop.
Linked List Operations on javascript
function Node(value){
this.value = value;
this.next = null;
}
function LinkedList() {
this.start = null;
this.length = 0;
}
LinkedList.prototype.push = function (val) {
if(this.start === null) {
this.start = new Node(val);
}
else {
var currentNode = this.start;
while (currentNode != null) {
if (currentNode.next == null) {
currentNode.next = new Node(val);
this.length++;
return true;
}
currentNode = currentNode.next;
}
}
}
LinkedList.prototype.searchByIndex = function (index) {
if (index >= this.length) {
return null;
}
if (index === 0) {
return this.start;
} else {
var currentNode = this.start.next;
for (var i = 1; i <= index; i++) {
if (i === index) {
return currentNode;
}
currentNode = currentNode.next;
}
}
}
LinkedList.prototype.search = function (val) {
if (this.start === null) {
return null;
}
else {
var currentNode = this.start;
while (currentNode != null) {
if (currentNode.value == val) {
return currentNode;
}
currentNode = currentNode.next;
}
}
}
LinkedList.prototype.remove = function (val) {
if(this.start === null) {
return false;
}
if(this.start.value === val) {
if (this.start.next) {
this.start = this.start.next;
} else {
this.start = null;
}
this.length--;
return true;
}
else {
var previousNode = this.start;
var currentNode = this.start.next;
while (currentNode != null) {
if (currentNode.value == val) {
previousNode.next = currentNode.next;
this.length--;
return true;
}
previousNode = currentNode;
currentNode = currentNode.next;
}
}
}
/*
Test your code through here(main func)
*/
function testCode() {
var test = [9,5,7,6,8,4,11,20,3,17,19,1,45,2];
var linkedList = new LinkedList();
var start = new Node(test[0]);
linkedList.start = start;
for(var i = 1; i < test.length; i++) {
linkedList.push(test[i]);
}
console.log('Linked List:',JSON.stringify(linkedList));
linkedList.remove(9);
console.log('Removed 9 from Linked List:',JSON.stringify(linkedList));
linkedList.remove(11);
console.log('Removed 11 from Linked List:',JSON.stringify(linkedList));
console.log('search 17:', linkedList.search(17));
console.log('search Non Existing:', linkedList.search('abc'));
console.log('searchByIndex index 6(value 3):', linkedList.searchByIndex(6));
console.log('searchByIndex Non Existent(length higher):', linkedList.searchByIndex(7776));
console.log('searchByIndex Non Existent(string):', linkedList.searchByIndex('abc'));
}
//running the main func to test the code...
testCode();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment