【问题标题】:Change my Linked List implentation to work on Leetcode problems?更改我的链表实现以解决 Leetcode 问题?
【发布时间】:2021-12-11 01:54:07
【问题描述】:

我正在解决这个 leetcode 问题:https://leetcode.com/problems/delete-node-in-a-linked-list/

编写一个函数来删除单链表中的一个节点。您将无法访问列表的头部,而是可以访问要直接删除的节点。

保证要删除的节点不是链表中的尾节点。

我找到了这个解决方案:

var deleteNode = function (node) {
    node.val = node.next.val;
    node.next = node.next.next;
};

这是我的链表实现:

class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

class LinkedList {
    constructor(value) {
        const newNode = new Node(value);
        this.head = newNode;
        this.tail = this.head;
        this.length = 1;
    }
}

我不知道为什么它不适用于我的 LL 实现。

【问题讨论】:

  • @RomainHippeau 你不能在没有头指针的情况下在单链表中执行此操作。
  • @RomainHippeau 他正在将值从下一个复制到当前,然后再删除下一个。
  • 如果删除倒数第二个节点,它变成了尾部,但LinkedList.tail仍然指向前一个尾部。
  • 而且你也不要减少包含它的LinkedList 的长度。

标签: javascript data-structures linked-list implementation


【解决方案1】:

在引用的问题中,只使用了这个节点类。这是 Leet Code 在注释块中显示的内容:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

第一个问题是val 属性在您的类中被称为value,因此您应该更改它在deleteNode 代码中出现的名称。

其次,Leet Code 没有引入也不需要链表类,这意味着您在 LinkedList 实例中拥有的所有数据都必须在您仅使用一个节点的情况下保持更新类,和上面的一样。

实际上,通过添加一个具有自己属性的LinkedList 类,你会遇到一个额外的问题:当deleteNode(node) 被调用时,你必须确定node 实际上是你的链表实例,而不是在其他链表中。如果你有两个链表怎么办?您如何知道作为参数传递给deleteNode 的节点属于哪个列表?

现在如果我们可以假设node 参数是您当前链表中的一个节点,我们可以将deleteNode 定义为一个方法。

附注:您的LinkedList 构造函数会立即创建一个节点,但这是一个坏主意:链表可以为空,因此从一个空列表开始(默认情况下),并使用通常的添加方法还要添加第一个节点。

class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

class LinkedList {
    constructor() {
        // A linked list could be empty, so don't create a node
        this.head = null;
        this.tail = null;
        this.length = 0;
    }
    append(val) {  // 
        if (!this.tail) this.head = this.tail = new Node(val);
        else this.tail = this.tail.next = new Node(val);
        this.length++;
    }
    deleteNode(node) {
        node.value = node.next.value; // Use value, not val
        node.next = node.next.next;
        // Also update the linked list properties:
        if (!node.next) this.tail = node;
        this.length--;
    }
    *[Symbol.iterator]() { // A generator to easily output the list's values
        for (let node = this.head; node; node = node.next) {
            yield node.value;
        }
    }
}

// demo
const list = new LinkedList(); 
list.append(1);
list.append(2);
list.append(3);
console.log("initial list:  ", ...list);
list.deleteNode(list.head.next); // Delete the 2
console.log("after deletion:", ...list);

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多