search
HomeBackend DevelopmentPython TutorialPretty printing linked lists in Python

Pretty printing linked lists in Python

Aug 28, 2023 am 08:33 AM
pythonLinked list printing

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()}")

Output

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

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!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use