Python two lines solution, copy value and then delete the next node.


  • 12
    C
    def deleteNode(self, node):
        node.val = node.next.val
        node.next = node.next.next

  • 0
    S

    Why doesn't it work?

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

    sorry I'm a beginner


  • 4
    M

    "node" is just a reference, like a pointer. node =node.next just changes node from pointing to original node to next node. But the nodelist itself doesn't change.


  • 0
    S

    Thanks! mgskai


  • 0
    M

    What happens when node is None or node.next is None? And why we do not need to "delete" the allocated memory for node in Python as we did in C++?


  • 1
    C

    When node is None or node is the last node, you should consider them separately. If the node is the last one, we have no other way except scanning from the beginning to the end, so the complexity is O(n), while this is the only case, other nodes can be done by replacing values, so the average complexity is still O(1). In Python, we don't need to contact with memory directly, the underlying memory manager will handle this for us. Here you can see the detailed description.


  • -1
    J

    I think one line is ok.

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

  • 0
    G

    Look, "delete a node (except the tail)"


  • 0
    E

    @caikehe

    May I ask why reverse the order will not work?

    def deleteNode(self, node):
    node.next = node.next.next
    node.val = node.next.val


  • 0
    I

    @enaj_25
    Your snippet fails because we are referencing node.next after updating it.


  • 0
    E

    @shintanoid I guess the leetcode test method is only test the node itself, since you only change the relationship between node.prev.next = node.next, but the node itself didn't change that means the node.val and node.next still have the original value, that's why doesn't work


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.