momo3141

Remove_N_after_M

Mar 5th, 2023
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const head1 = {
  2.    val:1,
  3.    next:{
  4.       val:2,
  5.       next:{
  6.          val:3,
  7.          next: {
  8.             val:4,
  9.             next:{
  10.                val:5,
  11.                next:null
  12.             }
  13.          }
  14.       }
  15.    }
  16. }
  17.  
  18. const removeNafterM = (head, N, M) => {
  19.    let counter = 1
  20.    let ref = head
  21.    while(counter < N)  {
  22.       if(ref.next ===null){
  23.          throw new Error('Starting point outside the list')
  24.       }
  25.       ref = ref.next
  26.       counter++
  27.    }
  28.    
  29.    secondRef = ref
  30.    finalCounter = counter+M
  31.    while(counter<=finalCounter) {
  32.       if(secondRef.next === null){
  33.          ref.next = null
  34.          return head
  35.       }
  36.       secondRef = secondRef.next
  37.       counter++
  38.    }
  39.    ref.next = secondRef;
  40.    return head;
  41. }
  42. console.log(removeNafterM(head1,10,2));
Advertisement
Add Comment
Please, Sign In to add comment