I made a linked list using the following code.
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List the master class contains a Node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
And added values to it as:
if __name__=='__main__':
# Start with the empty list
llist = LinkedList()
llist.head = Node(1)
llist.head.next = Node(2)
llist.head.next.next = Node('3a')
Then I tried to make a function to print the data of the linkedlist as:
def printl(llist):
temp = llist.head
while(temp):
return temp.data
temp = temp.next
But it returned only the first value i.e 1. How can I print all the data present in the linked list?
CodePudding user response:
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List the master class contains a Node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.node = None
def add_next_node(self, data):
next_node = Node(data)
next_node.next = self.node
self.node = next_node
def print_list(self):
temp = self.node
while (temp):
yield temp.data
temp = temp.next
ll = LinkedList()
ll.add_next_node(1)
ll.add_next_node(2)
ll.add_next_node(3)
ll.add_next_node(4)
for x in ll.print_list():
print (x)
4
3
2
1