Reference to javascript solution of leetcode - Add two numbers https://leetcode.com/problems/add-two-numbers/
Why List scope is not changed when head scope is changed i.e. when head.next is assigned to new node reference and head is assigned back to head.next, then why List.next didn't change and remained the same as the whole linked list
Pls refer to below solution -
Definition for singly-linked list.
function ListNode(val) {
this.val = val;
this.next = null;
}
@param {ListNode} l1
@param {ListNode} l2
@return {ListNode}
var addTwoNumbers = function(l1, l2) {
var List = new ListNode(0);
var head = List;
var sum = 0;
var carry = 0;
while(l1!==null||l2!==null||sum>0){
if(l1!==null){
sum = sum l1.val;
l1 = l1.next;
}
if(l2!==null){
sum = sum l2.val;
l2 = l2.next;
}
if(sum>=10){
carry = 1;
sum = sum - 10;
}
head.next = new ListNode(sum);
head = head.next;
sum = carry;
carry = 0;
}
return List.next;
};
I tried the below thing but it gave some different output below, b.next is changed when a.next is changed, Why so?
function value (val){ this.x = val;this.next = null;}
let a = new value(1);
console.log(a.x);
console.log(a.next, "a next");
let b = a;
console.log(b.x);
console.log(b.next,"b next")
a.next = 23;
console.log(a.next, "a next");
console.log(b.next,"b next")
VM1592:3 1
VM1592:4 null 'a next'
VM1592:6 1
VM1592:7 null 'b next'
VM1592:9 23 'a next'
VM1592:10 23 'b next'
List is not changed in above example but head did change? Why b is changed with a changed ? Why
CodePudding user response:
head
and List
are variables that hold references to the same ListNode
. A ListNode
is a mutable object. Therefore, when you change the properties of head
, say change its next
property, this is reflected also in
List`, since they both point to the same object.
Now, when you change the value of head
, say head = head.next
, List
still refers to the initial ListNode
. head
and List
aren't references of each other. Changing one itself doesn't change the other. They are just pointers to an object. Only changing the properties of the object itself is reflected in the other, so long as both point to the same object (at the beginning that is).