This code is not mine, I am just trying to understand it!
I need some help understanding what is happening in this lst2link
function.
So the function starts off by creating two ListNode
s in the variables cur
and dummy
and the then proceeds to build the linked list using the orginal cur
as the head. It returns dummy.next
. When I run this and see what is returned it appears that dummy.next
is the head of the linked list created using cur
. There does not appear to be anywhere indicating that dummy.next
points to the head of the linked list created in this function? How does it know to point there?
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def lst2link(lst):
cur = dummy = ListNode(0)
for e in lst:
cur.next = ListNode(e)
cur = cur.next
return dummy.next
CodePudding user response:
So the function starts off by creating two ListNodes in the variables cur and dummy
This is not true -- it creates one ListNode
, but assigns two variables to reference that same node.
As the list is built, the cur
variable is moved down the list, so that it always points to the last node. dummy
is never reassigned, so it continues to point at the original (first) node, which is not considered part of the final list that is returned.
Supposing that we call this function with the input [1, 2]
, the sequence of events looks something like this:
cur = dummy = ListNode(0)
# cur
# [0]
# dummy
cur.next = ListNode(1)
cur = cur.next
# cur
# [0] -> [1]
# dummy
cur.next = ListNode(2)
cur = cur.next
# cur
# [0] -> [1] -> [2]
# dummy
return dummy.next
# cur
# [0] -> [1] -> [2]
# dummy ^
# |
# return
CodePudding user response:
list2link function accepts a list of ListNode objects. It then declares two variables 'cur' and 'dummy' with a instantiated ListNode with value 0.
The function then iterates over the ListNode objects received in the list adding the first item as the 'next' or child variable of the 'cur' variable.
It then sets the cur variable to the just added child node. It repeats this adding the next item in the previous node as its child. Resulting in a tree like structure with every node having one child.
Although this code allows no way to access the parent node, so even though it has added it as a child, it can never go back up the list.
As well the returned value 'dummy.next' is only set in the objects init method to None, so this will only ever return None.