Skip to content

Instantly share code, notes, and snippets.

@rahul4coding
Created December 16, 2019 17:05
Show Gist options
  • Save rahul4coding/342d70c55498d02bd55cc06bd8482677 to your computer and use it in GitHub Desktop.
Save rahul4coding/342d70c55498d02bd55cc06bd8482677 to your computer and use it in GitHub Desktop.
Insert a Node at the head of a Linked List | JavaScript
//https://www.hackerrank.com/challenges/insert-a-node-at-the-head-of-a-linked-list/problem?h_r=next-challenge&h_v=zen
function insertNodeAtHead(head, data) {
var newNode = new SinglyLinkedListNode(data);
if(head==null){
head = newNode;
return head;
}else{
newNode.next = head
head = newNode;
return head;
}
}
@ACU017
Copy link

ACU017 commented Jul 13, 2023

I have a different version :

addToHead(val) {
let newHeadNode = new Node(val);
newHeadNode.next = this.head;
this.head = newHeadNode;
}

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