我需要一些有关Javascript内存如何工作的指针。在从链接列表的末尾删除第n个节点的实现中,我有一个占位符resultHead。
在代码的结尾,我有控制台日志resultHead,第一次是head的原始分配:
{“ val”:1,“ next”:{“ val”:2,“ next”:{“ val”:3,“ next”:{“ val”:4,“ next”:{“ val “:5,” next“:null}}}}}
但是第二次出现此行之后:
slow.next = slow.next.next
然后控制台注销:
{“ val”:1,“ next”:{“ val”:2,“ next”:{“ val”:3,“ next”:{“ val”:5,“ next”:null}} }}
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
if(head.next === null){return null}
// use resultHead as a place holder and its next is the actual head
let resultHead = new ListNode(null);
resultHead.next = head;
// find the difference between fast and slow pointer
let fast = resultHead;
let slow = resultHead;
for(let i=0; i<=n; i++){
fast=fast.next;
}
while(fast){
slow = slow.next
fast = fast.next
}
console.log(JSON.stringify(resultHead.next))
slow.next = slow.next.next
console.log(JSON.stringify(resultHead.next))
return resultHead.next;
};
removeNthFromEnd({"val":1,"next":{"val":2,"next":{"val":3,"next":{"val":4,"next":{"val":5,"next":null}}}}}, 2)
因此代码应删除带有node.val = 4
的节点
slow.next = slow.next.next
如何更改resultHead
的值?
我还尝试在不同的位置控制台resultHead
的日志,但是仅在slow.next = slow.next.next
更改了resultHead
的值之后。
答案 0 :(得分:2)
请记住,javascript通过引用传递对象。 resultHead.next = head表示修改resultHead.next从外部修改head。您将resultHead设置为慢速和快速,因此修改slow.next会修改head。
即
slow === resultHead
resultHead.next === head
slow.next === head