gpt4 book ai didi

python - 以简单的方式从单链表中删除节点

转载 作者:行者123 更新时间:2023-12-01 01:03:25 24 4
gpt4 key购买 nike

我正在通过一个简单的leetcode问题学习LinkedList Delete Node in a Linked List - LeetCode

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Given linked list -- head = [4,5,1,9], which looks like following:

enter image description here

Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.

Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.

Note:

  • The linked list will have at least two elements.
  • All of the nodes' values will be unique.
  • The given node will not be the tail and it will always be a valid node of the linked list.
  • Do not return anything from your function.

官方解决方案:

将要删除的节点的值替换为其后节点中的值,然后删除其后的节点。

# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next

我觉得麻烦,所以改成:

class Solution:
def deleteNode(self, node):
node= node.next

以简单的方式将下一个节点分配给当前节点

不幸的是,它报告了错误的答案。

我不明白为什么它不起作用。

逻辑没有错误:当前节点被下一个节点遮蔽,

最佳答案

这就是我们想要做的,删除节点:

前 -> 节点 -> 后 => 前 -> 后

因此,您应该做的是将 pre.nextnode 更改为 node.next。像:

pre.next = node.next

如果您执行node = node.next,它只会更改node引用。

对原来的ListNode没有任何影响。

但是在这种情况下我们无法获取 pre,因此我们必须将 node 值更改为 post,并删除 发布

希望对您有帮助,如有疑问请评论。 :)

关于python - 以简单的方式从单链表中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com