Pretty print Linked List in Python

Printing a linked list in a well-formatted and readable manner is essential for understanding and debugging purposes. Python provides several approaches to implement pretty print functionality for linked lists, making data structures more visually appealing and easier to comprehend.

By presenting the nodes and their connections in an organized way, developers can easily visualize the structure of the linked list, aiding in comprehension and efficient problem-solving.

Basic Pretty Print Implementation

Here's how to create a linked list with basic pretty print functionality ?

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

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

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

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

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

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

linked_list.pretty_print()
print(f"Length: {linked_list.get_length()}")
Node 1: 10
Node 2: 20
Node 3: 30
Node 4: 40
Node 5: 50
Length: 5

Enhanced Pretty Print with Arrows

For better visualization, we can add arrow symbols to show connections between nodes ?

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

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

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

    def pretty_print_arrows(self):
        if self.head is None:
            print("Empty list: None")
            return
        
        current = self.head
        result = []
        while current:
            result.append(str(current.data))
            current = current.next
        
        print(" -> ".join(result) + " -> None")

    def pretty_print_detailed(self):
        if self.head is None:
            print("Linked list is empty.")
            return
        
        print("Linked List Structure:")
        print("-" * 30)
        current = self.head
        position = 0
        
        while current:
            next_data = current.next.data if current.next else "None"
            print(f"Position {position}: Data = {current.data}, Next = {next_data}")
            current = current.next
            position += 1

# Example usage
linked_list = LinkedList()
linked_list.add_node(10)
linked_list.add_node(20)
linked_list.add_node(30)

print("Arrow format:")
linked_list.pretty_print_arrows()

print("\nDetailed format:")
linked_list.pretty_print_detailed()
Arrow format:
10 -> 20 -> 30 -> None

Detailed format:
Linked List Structure:
------------------------------
Position 0: Data = 10, Next = 20
Position 1: Data = 20, Next = 30
Position 2: Data = 30, Next = None

Pretty Print with Memory Addresses

To show memory locations and better understand pointer relationships ?

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

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

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

    def pretty_print_memory(self):
        if self.head is None:
            print("Empty linked list")
            return
        
        print("Memory Address View:")
        print("-" * 50)
        current = self.head
        node_num = 1
        
        while current:
            next_addr = hex(id(current.next)) if current.next else "None"
            print(f"Node {node_num}: Data={current.data}, Address={hex(id(current))}, Next={next_addr}")
            current = current.next
            node_num += 1

# Example usage
linked_list = LinkedList()
linked_list.add_node("A")
linked_list.add_node("B")
linked_list.add_node("C")

linked_list.pretty_print_memory()
Memory Address View:
--------------------------------------------------
Node 1: Data=A, Address=0x7f8b1c0a5d30, Next=0x7f8b1c0a5e80
Node 2: Data=B, Address=0x7f8b1c0a5e80, Next=0x7f8b1c0a5f40
Node 3: Data=C, Address=0x7f8b1c0a5f40, Next=None

Comparison of Pretty Print Methods

Method Best For Information Shown
Basic Print Simple debugging Node position and data
Arrow Format Visual flow understanding Data connections
Detailed Print Complete structure analysis Position, data, and next pointer
Memory Address Memory management debugging Actual memory locations

Conclusion

Pretty printing linked lists in Python enhances code readability and debugging efficiency. Choose arrow format for quick visualization, detailed format for comprehensive analysis, or memory address format for low-level debugging needs.

Updated on: 2026-03-27T09:48:41+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements