Skip to content

Instantly share code, notes, and snippets.

@jairocolondev
Forked from robgmerrill/FodU-36.js
Created July 12, 2021 00:59
Show Gist options
  • Save jairocolondev/5d8ab48d88272b4fe741dd1dadad3b12 to your computer and use it in GitHub Desktop.
Save jairocolondev/5d8ab48d88272b4fe741dd1dadad3b12 to your computer and use it in GitHub Desktop.
Linked List with Search Method by robgmerrill - https://repl.it/FodU/36
// linked list constructor function
function LinkedList() {
// initial creation has no nodes
this.head = null;
this.tail = null;
}
// node constructor function
// properties value, next previous
function Node(value, next, prev) {
this.value = value;
this.next = next;
this.prev = prev;
}
//create an instance of our Node
var node1 = new Node(100, 'node2', null);
// adding new value to prototype
LinkedList.prototype.addToHead = function(value) {
// create new node to add to head of linked list
// value is a parameter that is passed to the function; this.head refers to the previous head of the node because that is now next, null will be the previous value because this is the head
var newNode = new Node(value, this.head, null);
// already nodes present
if (this.head) {
// give old head a new head
this.head.prev = newNode;
} else {
// if no head node then this is both the head and the tail node
this.tail = newNode;
}
// set the head
this.head = newNode;
};
LinkedList.prototype.addToTail = function(value) {
var newNode = new Node(value, null, this.tail);
// already nodes present
if(this.tail) {
//give old tail a new tail
this.tail.next = newNode;
} else {
this.head = newNode;
}
// set the tail
this.tail = newNode;
}
LinkedList.prototype.removeHead = function() {
if (!this.head) return null;
var val = this.head.value;
this.head = this.head.next;
if (this.head) this.head.prev = null;
else this.tail = null;
return val;
};
LinkedList.prototype.removeTail = function() {
if(!this.tail) return null;
var val = this.tail.value;
this.tail = this.tail.prev;
if (this.tail) this.tail.next = null;
else this.head = null;
return val;
}
// var ll = new LinkedList();
// ll.addToHead('1');
// ll.addToHead('2');
// ll.addToHead('3');
// console.log(ll.removeTail());
LinkedList.prototype.search = function(searchValue) {
var currentNode = this.head;
while (currentNode) {
if (currentNode.value === searchValue) {
return currentNode.value;
} else {
currentNode = currentNode.next;
}
}
return null;
};
var myLL = new LinkedList();
myLL.addToHead(123);
myLL.addToHead(70);
myLL.addToHead('hello');
myLL.addToTail(19);
myLL.addToTail('world');
myLL.addToTail(20);
myLL.search(70);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment