Pretty print Linked List in Python


Printing a linked list in a well-formatted and readable manner is essential for understanding and debugging purposes which can easily be done using the Pretty print function of Python. This article explores how to implement a pretty print functionality for linked lists in Python.

By presenting the nodes and their associated information in an organized and visually appealing way, developers can easily visualize the structure of the linked list, aiding in comprehension and efficient problem-solving. Discover how to enhance the clarity of your linked lists with Python's powerful features.

How to pretty print Linked List in Python?

Below are the steps that we will be following to pretty print a linked list in Python −

Steps (Algorithm)

  • First, we define the class named Node, which represents a single node in the linked list. Each node has the next pointer and data attributes.

  • Next, we define the LinkedList class, which manages the linked list. It has one attribute head, which points to the first node in the list. Initially, the head is set to None to indicate an empty list.

  • The add_node method is used to add nodes to the linked list. It takes a data parameter as input. Inside the method, we create a new Node object with the given data. If the linked list is empty (i.e., head is None), we set the new node as the head. Otherwise, we traverse to the end of the list by starting from the head and moving to the next node until we reach the last node. Finally, we append the new node to the end of the list by updating the next attribute of the last node.

  • The pretty_print method is used to print the linked list in a readable format. If the linked list is empty (i.e., head is None), it prints a message indicating that the list is empty. Otherwise, it traverses through each node starting from the head. It keeps track of the node number using a count variable and prints the data of each node along with its corresponding number. The method continues this process until it reaches the end of the list.

  • The get_length method calculates and returns the length of the linked list. It starts from the head and traverses through each node, incrementing a length variable for each node encountered. Finally, it returns the total length of the list.

  • We then call the pretty_print method on the linked_list object to display the contents of the list. This will print each node's data along with its corresponding number.

  • Finally, we call the get_length method on the linked_list object to calculate and print the length of the list.

If we want to modify the program, follow the steps given below −

  • You can add additional methods to perform various operations on the linked list, such as searching for a specific value, deleting a node, or inserting a node at a specific position. These methods can be added to the LinkedList class.

  • If you want to customize the node class, you can add more attributes to the Node class to store additional information.

  • You can enhance the pretty_print method to display more information about each node. For example, you can print the memory address of each node or print an arrow symbol to indicate the links between nodes.

  • You can modify the add_node method to insert nodes at the beginning of the list instead of the end.

  • You can implement methods to reverse the linked list, merge two linked lists, or split the linked list into two separate lists.

Example

In the below example usage, we create a LinkedList object, add nodes with values 10, 20, 30, 40, and 50, and then call the pretty_print method to display the list. Finally, we call the get_length method to retrieve the length of the linked list and print it.

class Node:
   def __init__(self, d):
      self.d = d
      self.next = None

class LinkedList:
   def __init__(self):
      self.head = None

   def add_node(self, d):
      new_node = Node(d)
      if self.head is None:
         self.head = new_node
      else:
         curr = self.head
         while curr.next:
              curr = curr.next
         curr.next = new_node

   def pretty_print(self):
      if self.head is None:	
         print("Linked list is empty.")
      else:
         curr = self.head
         count = 1
         while curr:
            print(f"Node {count}: {curr.d}")
            curr = curr.next
            count += 1

   def get_length(self):
      length = 0
      curr = self.head
      while curr:
         length += 1
         curr = curr.next
      return length


# Example usage
linked_list1 = LinkedList()
linked_list1.add_node(10)
linked_list1.add_node(20)
linked_list1.add_node(30)
linked_list1.add_node(40)
linked_list1.add_node(50)

linked_list1.pretty_print()
print(f"Length: {linked_list1.get_length()}")

Output

Node 1: 10
Node 2: 20
Node 3: 30
Node 4: 40
Node 5: 50
Length: 5

Conclusion

In conclusion, we can say that by implementing a pretty print functionality for linked lists in Python, developers can greatly improve the readability and visualization of their data structures. Clear and organized representation of linked lists facilitates easier comprehension and debugging, enabling efficient problem-solving. With Python's flexibility, enhancing the clarity of linked lists becomes a straightforward task for any programmer.

Updated on: 25-Jul-2023

614 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements