Skip to content

Instantly share code, notes, and snippets.

@11ma
Created July 19, 2020 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 11ma/11fee27eff34e0c5ce9d22b631e1904d to your computer and use it in GitHub Desktop.
Save 11ma/11fee27eff34e0c5ce9d22b631e1904d to your computer and use it in GitHub Desktop.
Linkedlist
// source https://codeburst.io/linked-lists-in-javascript-es6-code-part-1-6dd349c3dcc3
class Node{
constructor(data, next = null){
this.data = data,
this.next = next
}
}
class LinkedList{
constructor(){
this.head = null;
}
}
// A list object is created with a property head, currently pointing at null
let list = new LinkedList();
// Singly list - inserting at the beginning of a singly list
LinkedList.prototype.insertAtBeginning = function(data){
// A newNode object is created with property data and next = null
let newNode = new Node(data);
// The pointer next is assigned head pointer so that both pointers now point at the same node.
newNode.next = this.head;
// As we are inserting at the beginning, the head pointer needs to now point at the newNode.
this.head = newNode;
return this.head;
}
// Singly list - inserting at the end of a singly list
LinkedList.prototype.insertAtEnd = function(data){
// A newNode object is created with property data and next=null
let newNode = new Node(data);
// When head = null i.e. the list is empty, then head itself will point to the newNode.
if(!this.head){
this.head = newNode;
return this.head;
}
// Else, traverse the list to find the tail (the tail node will initially be pointing at null), and update the tail's next pointer.
let tail = this.head;
while(tail.next !== null){
tail = tail.next;
}
tail.next = newNode;
return this.head;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment