I am studying Data Structures and Algorithms. I encountered some confusion below.
from typing import *
class Node:
curr_node_value: Any
next_node: Node
def __init__(self, curr_node_value: Any = None):
# a node can hold a current value and by default its next node is None
# however we can assign values to the next of a node, but the next must be of object node as denoted
# note the distinction between curr node value and next node, they are diff
self.curr_node_value = curr_node_value
self.next_node = None
class LinkedList:
def __init__(self):
# key point is that end of every llist, it points to None always
self.head = None
ll1_first = Node(1)
ll1_second = Node(2)
ll1_third = Node(4)
ll2_first = Node(1)
ll2_second = Node(3)
ll2_third = Node(4)
# create llist 1
ll1 = LinkedList()
ll1.head = ll1_first
ll1.head.next_node = ll1_second
ll1.head.next_node.next_node = ll1_third
# create llist 2
ll2 = LinkedList()
ll2.head = ll2_first
ll2.head.next_node = ll2_second
ll2.head.next_node.next_node = ll2_third
merged_sorted_llist = LinkedList()
ll1_temp_curr_node = ll1.head
ll2_temp_curr_node = ll2.head
while ll1_temp_curr_node is not None and ll2_temp_curr_node is not None:
print(ll1_temp_curr_node.curr_node_value)
ll1_curr_node = ll1_temp_curr_node
ll2_curr_node = ll2_temp_curr_node
if ll1_curr_node.curr_node_value <= ll2_curr_node.curr_node_value:
merged_sorted_llist.head = ll1_curr_node
#print(merged_sorted_llist.head.next_node.curr_node_value)
merged_sorted_llist.head.next_node = ll2_curr_node
ll1_temp_curr_node = ll1_temp_curr_node.next_node
ll2_temp_curr_node = ll2_temp_curr_node.next_node
The code is a subset of a larger question but I cannot understand clearly why when you print print(ll1_temp_curr_node.curr_node_value) it gives you 1, 1, 3 instead of 1, 2, 4. I did extensive debugging and if you comment out merged_sorted_llist.head.next_node = ll2_curr_node it will print out 1, 2, 4.
After googling, I came to read this post and believe I messed up somewhere in variable assigning, especially if I set the attributes. It is still not very obvious to me where.