python链表中删除一个节点数据_Python:如何在O(1)tim中只删除单链表中的节点...

我已经阅读了下面的帖子,但他们没有回答我的问题。在

这个post差不多可以解释了。@Rishikesh Raje投票最多的回答是,删除单链表中的最后一个节点是[...] is generally not possible.

为什么一般不可能,而不仅仅是“不可能”?我的问题是理论本身以及它如何适用于Python?这个问题是给C的

另外,我的另一个问题是链表只有一个节点的情况下,它也是最后一个节点。在

背景:我正在LeetCode上解决这个problem。虽然它没有要求删除最后一个案例的情况,我尝试了,但似乎无法得到它,因为有些功能我无法确定。如果你能在这里指点迷津,我将不胜感激。我添加了一个方法来打印用于调试的值。在

问题是:Write a function to delete a node (except the tail) in a singly linked

list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the

third node with value 3, the linked list should become 1 -> 2 -> 4

after calling your function.

我的代码可以达到所需的结果1->2->4:# Definition for singly-linked list.

class ListNode(object):

def __init__(self, x):

self.val = x

self.next = None

class Solution(object):

def deleteNode(self, node):

"""

:type node: ListNode

:rtype: void Do not return anything, modify node in-place instead.

"""

nextNode = node.next

if nextNode:

node.val = nextNode.val

node.next = nextNode.next

else:

node = None

def listToString(self, head):

string = ""

while head:

string += str(head.val) + "\n"

head = head.next

return string

head = ListNode(1)

head.next = ListNode(2)

head.next.next = ListNode(3)

head.next.next.next = ListNode(4)

solution = Solution()

print(solution.listToString(head))

print('-'*10)

node = head.next.next

solution.deleteNode(node)

print(solution.listToString(head))

运行这个可以让我:

^{pr2}$

但当我把底部改为:head = ListNode(1)

solution = Solution()

print(solution.listToString(head))

print('-'*10)

node = head

solution.deleteNode(head)

print(solution.listToString(head))

我明白了1

----------

1

问题是:

为什么1不打印而{}?请注意,这个链表只有一个节点(这意味着它是最后一个节点),这就是传递给函数的内容。

能做到吗?

如果是,我应该做些什么修改?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值