Reputation: 507
I'm a beginner to programming and I'm trying to understand the following code:
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
node.val = node.next.val
node.next = node.next.next
My intuition for the code is the following: I understand that node is a reference to an element in the linked list and node.next is a pointer to the next node. I also understand that node.val sets the value of the current node to the value of the next node. What exactly is the purpose of
node.next = node.next.next?
Upvotes: 0
Views: 56
Reputation: 6633
Imagine the following linked list nodes (where n2 is the node you're removing)
... -> n1 -> n2 -> n3 -> ...
node -^ ^ ^- node.next.next
|
node.next
So if you set node.next = node.next.next
you get this:
n2
|
v
... -> n1 -> n3 -> ...
node -^ ^
|
node.next
And since now nothing is referring to n2 once the function returns it will be garbage collected.
Upvotes: 3
Reputation: 4528
It means that the link to next node is removed and this node links to next.next node , it means the next node is deleted and its value replace with this node value. for example we have following list:
1->2->3->4
1.next(2) = 1.next.next(3)
so list updatedt to:
1->3->4
Upvotes: 1
Reputation: 68
NodeA -> NodeB -> NodeC
So currently NodeA.next is NodeB
by assinging NodeA.next = NodeA.next.next we get NodeA.next = NodeB.next which makes
NodeA.next = NodeC
so the chain is now
NodeA -> NodeC
Upvotes: 2