└── linked-list.js /linked-list.js: -------------------------------------------------------------------------------- 1 | // const n1 = { 2 | // data:100 3 | // }; 4 | 5 | // const n2 = { 6 | // data: 200 7 | // }; 8 | 9 | 10 | // n1.next = n2; 11 | 12 | // console.log(n1); 13 | 14 | class Node { 15 | constructor(data,next=null){ 16 | this.data=data; 17 | this.next =next; 18 | } 19 | } 20 | 21 | class LinkedList { 22 | constructor(){ 23 | this.head = null; 24 | this.size =0 25 | } 26 | //insert first node 27 | insertFirst(data){ 28 | this.head = new Node(data,this.head); 29 | this.size++; 30 | } 31 | 32 | //insert last node 33 | insertLast(data){ 34 | let node = new Node(data); 35 | let current; 36 | 37 | //if empty , make head 38 | if (!this.head){ 39 | this.head = node; 40 | }else{ 41 | current=this.head; 42 | 43 | 44 | while(current.next){ 45 | current = current.next; 46 | } 47 | 48 | current.next = node; 49 | } 50 | 51 | this.size++; 52 | 53 | } 54 | 55 | 56 | 57 | //insert at index 58 | 59 | insertAt( data,index){ 60 | //if index is out of range 61 | if (index > 0 && index > this.size){ 62 | return; 63 | } 64 | 65 | //if first index 66 | if(index ===0){ 67 | this.head = new Node(data,this.head); 68 | return; 69 | } 70 | const node = new Node(data); 71 | let current,previous; 72 | 73 | //set current to first 74 | current = this.head; 75 | let count=0; 76 | 77 | while(countthis.size){ 108 | return; 109 | } 110 | let current =this.head; 111 | let previous; 112 | let count =0; 113 | 114 | // remove first 115 | if(index ===0){ 116 | this.head =current.next; 117 | }else{ 118 | while(count