Skip to content

Instantly share code, notes, and snippets.

@robgmerrill
Last active February 18, 2017 16:16
Show Gist options
  • Save robgmerrill/30cc398b572c8f1cd6751d5a1c143743 to your computer and use it in GitHub Desktop.
Save robgmerrill/30cc398b572c8f1cd6751d5a1c143743 to your computer and use it in GitHub Desktop.
Linked List add to head/tail by robgmerrill - https://repl.it/FodU/19
// 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;
};
var ll = new LinkedList();
// creation of first node
ll.addToHead(100);
// console.log(ll);
// creation of new head
ll.addToHead(200);
// console.log(ll);
ll.addToHead(300);
// console.log(ll);
// add to tail method
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;
}
ll.addToTail(500);
// console.log(ll);
var myLL = new LinkedList();
myLL.addToTail(10);
myLL.addToTail(20);
myLL.addToTail(30);
// console.log(myLL.tail.prev.prev);
myLL.addToHead(100);
console.log(myLL);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment