remove-elements.js (1312B)
1 //Remove all nodes of the linked list where the value 2 //stored is equal to the value val that is passed as 3 //an input to the function. Then return the head of the list 4 //My solution iterates through the list checking if a node 5 //is equal to the value passed in. If it is then the refrence 6 //to the previous node sets it's pointer to the next node after the current thus 7 //cutting it out of the list. Given this implementation 8 //the time compexity of this is O(n) where n is the number 9 //of elements in the linked list. 10 //Time: 75ms Beats: 70.73% 11 //Memory: 46.4MB Beats: 78.22% 12 13 /** 14 * Definition for singly-linked list. 15 * function ListNode(val, next) { 16 * this.val = (val===undefined ? 0 : val) 17 * this.next = (next===undefined ? null : next) 18 * } 19 */ 20 /** 21 * @param {ListNode} head 22 * @param {number} val 23 * @return {ListNode} 24 */ 25 var removeElements = function(head, val) { 26 let itr = head; 27 let itr1 = new ListNode(); 28 29 while(head?.val == val || head == null){ 30 if(head == null){ 31 return null; 32 } 33 else{ 34 head = head.next; 35 } 36 } 37 38 39 while(itr != null){ 40 if(itr.val == val){ 41 itr1.next = itr.next; 42 itr = itr1; 43 } 44 itr1 = itr; 45 itr = itr.next; 46 } 47 48 49 return head; 50 };