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