Single Linked Lists

Run Settings
LanguageJavaScript
Language Version
Run Command
/* What is the linked lists [5] [10] [2] head tail => null */ const basket = ['apples','grapes','pears']; /* linked list : apples --> grapes --> pears prepend O(1) append O(1) lookup O(n) insert O(n) delete O(n) We need to understand about the LinkedList */ /* how object will work in the javascript and pointer pointer is the reference in the memory. */ const obj1 = {a : true}; const obj2 = obj1; obj1.a = 'booya'; console.log('1', obj1); console.log('2',obj2); /* Very first link list data structure. 10 --> 5 --> 16 */ /*let myLinkedList = { head: { value : 10, next: { value : 5, next: { value : 16, next : null } } } }*/ class LinkedList{ constructor(value){ this.head = { value : value, next: null } this.tail = this.head; this.length = 1; } append(value) { //code here const newNode = { value :value , next : null }; this.tail.next = newNode; this.tail = newNode; this.length++; return this; } prepend(value){ const newNode = { value :value , next : null }; newNode.next = this.head; this.head = newNode; this.length++; return this; } insert(index, value){ //check my parameter if(index >= this.length) { return this.append(value); } const newNode ={ value : value, next : null }; const leader = this.traverseToIndex(index-1); const holdingPointer = leader.next; leader.next = newNode; newNode.next = holdingPointer; this.length++; return this.printList(); } traverseToIndex(index) { //check params let counter= 0 ; let currentNode = this.head; while(counter !== index) { currentNode = currentNode.next; counter++; } return currentNode; } printList(){ const array = []; let currentNode = this.head; while(currentNode !== null ) { array.push(currentNode.value); currentNode = currentNode.next; } return array; } remove(index){ //check params const leader = this.traverseToIndex(index-1); const unWantedNode = leader.next; leader.next = unWantedNode.next; this.length--; return this.printList(); } } const myLinkedList = new LinkedList(10); myLinkedList.append(5); myLinkedList.append(16); myLinkedList.prepend(1); myLinkedList.insert(3,44); //myLinkedList.remove(2); console.log(myLinkedList.printList());
Editor Settings
Theme
Key bindings
Full width
Lines