在链表中实现删除节点时对象的内存的Javascript更改

时间:2019-03-24 04:00:14

标签: javascript javascript-objects singly-linked-list

我需要一些有关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的值之后。

1 个答案:

答案 0 :(得分:2)

请记住,javascript通过引用传递对象。 resultHead.next = head表示修改resultHead.next从外部修改head。您将resultHead设置为慢速和快速,因此修改slow.next会修改head。

slow === resultHead
resultHead.next === head
slow.next === head