I am trying to implement Single Linked List on Python and the Code below works fine but I can not understand how:
class Node(object):
def __init__(self, data=None, ):
self.value = data
self.next = None
class LinkedList1(object):
def __init__(self, data=None):
self.head = Node(data)
self.tail = self.head
self.length = 1
def append(self, data):
self.tail.next = Node(data)
self.tail = self.tail.next
self.length += 1
return self
def show_list(self):
head_copy = self.head
while head_copy is not None:
print(head_copy.value)
head_copy = head_copy.next
When we test it:
linkin = LinkedList1(10)
linkin.append(20)
linkin.append(30)
linkin.append(40)
linkin.show_list()
output :
10
20
30
40
What I don't understand is append function. I know self.tail referencing self.head but how come sefl.tail.next adds the new Node(data) to the at the last next, in my logic without a loop it should add to first next.
Plus if we write the function this way:
def append(self, data):
self.head.next = Node(data)
self.tail = self.head.next
self.length += 1
return self
This doesn't work even if self.tail reference to self.head.
I know I am missing something here. Can you help me understand?
Thank you.