Home > Backend Development > Python Tutorial > Pretty printing linked lists in Python

Pretty printing linked lists in Python

PHPz
Release: 2023-08-28 08:33:09
forward
1433 people have browsed it

Pretty printing linked lists in Python

Printing a linked list in a well-formatted and readable way is crucial for understanding and debugging purposes, and this can be easily done using Python’s Pretty print function. This article explores how to implement pretty printing of linked lists in Python.

By presenting nodes and their related information in an organized and visually appealing way, developers can easily visualize the structure of linked lists, helping to understand and effectively solve problems. Learn how to use the power of Python to improve the clarity of your linked lists.

How to pretty print a linked list in Python?

Here are the steps we take to pretty print a linked list in Python -

Steps (algorithm)

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

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

  • add_node method is used to add nodes to the linked list. It takes data parameters as input. Inside this method, we create a new Node object with the given data. If the linked list is empty (i.e. the head is None), we set the new node as the head. Otherwise, we start from the beginning and move to the next node until we reach the last node, thus traversing to the end of the list. Finally, we append the new node to the end of the list by updating the last node's next property.

  • 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 linked list is empty. Otherwise, traverse each node from the beginning. It keeps track of node numbers using a count variable and prints the data for each node and its corresponding number. The method will continue this process until it reaches the end of the list.

  • get_lengthThe method calculates and returns the length of the linked list. It traverses each node starting at the head, incrementing a length variable for each node encountered. Finally, it returns the total length of the list.

  • Then, we call the pretty_print method on the linked_list object to display the contents of the list. This will print the data for each node and its corresponding number.

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

If we want to modify the program, please follow the steps 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 location. These methods can be added to the LinkedList class.

  • If you want to customize the node class, you can add more properties 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 arrow symbols to indicate 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 a linked list, merge two linked lists, or split a linked list into two separate lists.

Example

In the example usage below, 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()}")
Copy after login

Output

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

in conclusion

In summary, we can say that by implementing pretty printing functionality for linked lists in Python, developers can greatly improve the readability and visualization of their data structures. A clear and organized linked list representation makes understanding and debugging easier, allowing for efficient problem solving. With Python's flexibility, enhancing the clarity of linked lists is a simple task for any programmer.

The above is the detailed content of Pretty printing linked lists in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template