Issue
I've been practicing link list but can't understand what ''self.head'' actually refers. Is it the first value in a list at index 0? And how can I print data inside the head?
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class Linkedlist:
def __init__(self):
self.head = None
def print_var(self):
itr = self.head
print(itr.data)
def insert_at_begining(self, data):
node = Node(data, self.head)
self.head = node
if __name__ = '__main__':
ll = Linkedlsit()
ll.insert_at_begining(3)
ll.insert_at_begining(4)
ll.insert_at_begining(6)
ll.insert_at_begining(8)
ll.print()
If I'm to call print fuction function, it will through an error. (Say, linklist is not empty)
Solution
self.head
refers to the first Node
in the list. From there, you can "walk" the list with something like:
current_node = ll.head
while current_node:
print(f"Current node data: {current_node.data}")
current_node = current_node.next
print("Reached End of List")
Answered By - Cargo23
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.