+ 1

Q: Nodes

why do we return dummy.next if it looks like we are doing the changes on tail, not the dummy? is it because it points to the same object in memory? const h = new Node(30); // 30 const p = new Node(15); const q = new Node(67); p.next = q; // 15 -> 67 mergeLists(h, p); // 15 -> 30 -> 67 class Node { constructor(val) { this.val = val; this.next = null; } } ////////⭐⭐⭐⭐⭐⭐⭐⭐⭐////////// const mergeLists = (head1, head2) => { let dummyHead = new Node(null); let tail = dummyHead; let current1 = head1; let current2 = head2; while (current1 !== null && current2 !== null) { if (current1.val < current2.val) { tail.next = current1; current1 = current1.next; } else { tail.next = current2; current2 = current2.next; } tail = tail.next; } if (current1 !== null) tail.next = current1; if (current2 !== null) tail.next = current2; return dummyHead.next; //🤔 };

20th Sep 2022, 1:41 AM
Jace🎭
Jace🎭 - avatar
1 Resposta
+ 1
dummyHead is the suspension point to which the merged list gets attached. The tail object always points to the last object in the new list. But a list is referenced from the head not the tail. Thus the first element in the list is the object next to the suspension point. And that is dummyHead.next
20th Sep 2022, 6:03 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar