print_list is a class method, so it will take self as an argument and print out the entries of a linked list. We will start from the head pointer and print out the data component of the node and then move to the next node. We’ll keep a check on the next node to make sure it is not None. If it’s not, we move to the next node. This way, we keep printing out data until we’ve hit the null terminating component of the linked list. Let’s implement this in Python!
xxxxxxxxxx
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
llist = LinkedList()
llist.append("A")
llist.append("B")
llist.append("C")
llist.append("D")
llist.print_list()
There you go! We initialize cur_node equal to the head of the linked list. Then we use a while loop which keeps running and printing the data if cur_node is not equal to None.
In the code above, we append four elements to the linked list. You can see this for yourself in the output.
Now we’ll move on to another method of inserting elements in a linked list.
To verify the append method, we will need to print the circular linked list. Let’s see how we would do this. Check out the code below:
xxxxxxxxxx
def print_list(self):
cur = self.head
while cur:
print(cur.data)
cur = cur.next
if cur == self.head:
break
xxxxxxxxxx
def print_list(self):
cur = self.head
while cur:
print(cur.data)
cur = cur.next