OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Modifications not propagating through object reference

  • Thread starter Thread starter suresh subedi
  • Start date Start date
S

suresh subedi

Guest
Here since the pointers fast and slow are referencing the same object dummy, why do the modificaitons in slow donot modify the fast pointer?


Code:
function ListNode(val, next) {
  this.val = (val === undefined ? 0 : val)
  this.next = (next === undefined ? null : next)
}

var removeNthFromEnd = function(head, n) {
  let dummy = new ListNode(0);
  dummy.next = head;

  let slow = dummy;
  let fast = dummy;
  slow = slow.next
  console.log(fast)

  for (let i = 0; i <= n; i++) {
    fast = fast.next;
  }

  while (fast !== null) {
    slow = slow.next;
    fast = fast.next;
  }

  return dummy.next;
};

removeNthFromEnd({
  val: 1,
  next: {
    val: 2,
    next: {
      val: 3,
      next: {
        val: 4,
        next: {
          val: 5,
          next: null
        }
      }
    }
  }
}, 2)

This type of behaviour does not occur when i directly assign object to variables

<p>Here since the pointers fast and slow are referencing the same object dummy, why do the modificaitons in slow donot modify the fast pointer?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}

var removeNthFromEnd = function(head, n) {
let dummy = new ListNode(0);
dummy.next = head;

let slow = dummy;
let fast = dummy;
slow = slow.next
console.log(fast)

for (let i = 0; i <= n; i++) {
fast = fast.next;
}

while (fast !== null) {
slow = slow.next;
fast = fast.next;
}

return dummy.next;
};

removeNthFromEnd({
val: 1,
next: {
val: 2,
next: {
val: 3,
next: {
val: 4,
next: {
val: 5,
next: null
}
}
}
}
}, 2)</code></pre>
</div>
</div>
</p>
<p>This type of behaviour does not occur when i directly assign object to variables</p>
 

Latest posts

M
Replies
0
Views
1
Mohit Pant
M
Top