class Node:
def __init__(self, data):
self.data = data
self.ref = None
def Print_LL(linkedlist):
if linkedlist is None:
print("LinkedList is empty!!")
else:
while linkedlist is not None:
print(linkedlist.data)
linkedlist = linkedlist.ref
def arr_to_LL(arr, n):
linkedlist = None
for i in range(0,n):
new_node = Node(arr[i])
if linkedlist is None:
linkedlist = new_node
else:
head = linkedlist
while head.ref is not None:
head = head.ref
head.ref = new_node
return linkedlist
why to take "head" variable? why cant we continue with linkedlist
>Solution :
linkedlist is a reference to the head of the list. head, despite the name, is just a reference to the end of the list, or more specifically to the node to which you’ll attach a new node. A better definition of arr_to_LL might be
def arr_to_LL(arr):
head = None
for v in arr:
new_node = Node(v)
if head is None:
head = new_node
else:
curr.ref = new_node
curr = new_node
return head
This for loop has two invariants:
headalways refers to the front of the (possibly empty) linked list.curr(once defined) always refers to the end of the linked list.
As you iterate over the array, you simply append a new node to the end, then update the end.
If you use the common convention of an empty linked list represented by a dummy node, it becomes even simpler, as now you don’t need a special case for head is None.
def arr_to_LL(arr):
# We'll store the length in the dummy node, because why not?
head = curr = Node(0)
for v in arr:
curr.ref = Node(v)
curr = new_node
head.data += 1
return head