Skip to content

Instantly share code, notes, and snippets.

@robgmerrill
Last active February 18, 2017 15:50
Show Gist options
  • Save robgmerrill/9182721562b9e73ae56c9c837130e28d to your computer and use it in GitHub Desktop.
Save robgmerrill/9182721562b9e73ae56c9c837130e28d to your computer and use it in GitHub Desktop.
Add to Head Method on Linked list
// 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);
@robgmerrill
Copy link
Author

Created a linked list and implemented "add to head function"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment