Here is the definition of ListNote class in LeetCode:
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
For the code:
result = ListNode(0)
#result = 0 -> None
result_tail = result
#result_tail = 0 -> None
result_tail.next = ListNode(1)
#result_tail = 0 -> 1 -> None
#result = 0 -> 1 -> None
result_tail = result_tail.next
#result_tail = 1 -> None
#result = 0 -> 1 -> None
result_tail.next = ListNode(2)
#result_tail = 1 -> 2 -> None
#result = 0 -> 1 -> 2 -> None
result_tail = result_tail.next
#result_tail = 2 -> None
#result = 0 -> 1 -> 2 -> None
The values in comments are from my guessing. I cannot understand the step
result_tail = result_tail.next
result_tail = result is pass by reference, so when result_tail becomes 1 -> None, result should also become 1 -> None. Why does result still keep 0 -> 1 -> None? And when result_tail becomes 1 -> 2 -> None, why does result extend its tail to 0 -> 1 -> 2 -> None?
result_tail = result_tail.next
is something like
result_tail = result.next.next
Can anyone tell me the logic here?