杰瑞科技汇

Python listNode是什么?如何使用?

Of course! In Python, there is no built-in ListNode class. It's a custom data structure that you define yourself to represent a node in a Linked List.

Python listNode是什么?如何使用?-图1
(图片来源网络,侵删)

Let's break down what a ListNode is, how to create it, and how to use it.

What is a ListNode?

A ListNode is the fundamental building block of a Linked List. Unlike a Python list (which is an array), where elements are stored in contiguous memory locations, a linked list stores elements in separate nodes that are linked together.

Each ListNode object typically contains two things:

  1. Data: The actual value the node holds (e.g., an integer, a string, an object).
  2. Next (or Next Pointer): A reference (or pointer) to the next node in the sequence. The last node in the list has its next pointer set to None.

This structure looks like this: [ Data | Next ] -> [ Data | Next ] -> [ Data | None ]

Python listNode是什么?如何使用?-图2
(图片来源网络,侵删)

How to Define a ListNode Class

You define a ListNode class using a simple Python class. It's common practice to include a helper method to make printing the list easier for debugging.

Here is the standard definition:

class ListNode:
    """
    A node in a singly-linked list.
    """
    def __init__(self, val=0, next=None):
        """
        Initializes a ListNode.
        Args:
            val (any): The data value of the node.
            next (ListNode, optional): The reference to the next node. Defaults to None.
        """
        self.val = val
        self.next = next
    def __repr__(self):
        """
        Provides a developer-friendly string representation of the node.
        This helps when printing the list for debugging.
        """
        # This creates a string like "ListNode(1) -> ListNode(2) -> None"
        nodes = []
        current = self
        while current:
            nodes.append(f"ListNode({current.val})")
            current = current.next
        return " -> ".join(nodes) + " -> None"

Explanation:

  • __init__(self, val=0, next=None): This is the constructor.
    • self refers to the instance of the class being created.
    • val is the data you want to store. It defaults to 0.
    • next is the reference to the next ListNode. It defaults to None, which is perfect for creating the tail of a list or a single-node list.
  • __repr__(self): This special method returns an "official" string representation of an object. By defining it, when you type print(my_list_head), Python will automatically call this method to give you a readable output of the entire list.

How to Create and Use ListNode Objects

Now let's see how to create instances of this class and link them together to form a linked list.

Example 1: Creating a Simple List

Let's create the list 1 -> 2 -> 3.

# Step 1: Create the individual nodes
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
# Step 2: Link the nodes together
# The 'next' of node1 points to node2
node1.next = node2
# The 'next' of node2 points to node3
node2.next = node3
# The 'next' of node3 is already None by default, so it's the end of the list.
# To "access" the entire list, you only need a reference to the first node, the "head".
head = node1
# Now, let's print the list using our __repr__ method
print(head)
# Expected Output: ListNode(1) -> ListNode(2) -> ListNode(3) -> None
# You can traverse the list manually
current = head
while current:
    print(f"Current node value: {current.val}")
    current = current.next
# Expected Output:
# Current node value: 1
# Current node value: 2
# Current node value: 3

Example 2: Creating a List with a Loop

It's very common to create a helper function to build a list from a standard Python list. This makes testing much easier.

def create_linked_list(items):
    """
    Creates a linked list from a Python list of items.
    Returns the head of the linked list.
    """
    if not items:
        return None
    # Create the head node
    head = ListNode(items[0])
    current = head
    # Iterate through the rest of the items and link them
    for item in items[1:]:
        current.next = ListNode(item)
        current = current.next
    return head
# --- Usage ---
# Create a list from [10, 20, 30, 40]
my_list_head = create_linked_list([10, 20, 30, 40])
print("The created linked list:")
print(my_list_head)
# Expected Output: The created linked list:
# ListNode(10) -> ListNode(20) -> ListNode(30) -> ListNode(40) -> None

Common Operations on a Linked List (using ListNode)

Here are some fundamental operations you'll perform.

Traversing the List

This is the process of visiting every node in the list, usually to find a value or print it out.

def traverse_list(head):
    """Prints the values of all nodes in the list."""
    current = head
    elements = []
    while current:
        elements.append(str(current.val))
        current = current.next
    print(" -> ".join(elements) + " -> None")
traverse_list(my_list_head)
# Expected Output: 10 -> 20 -> 30 -> 40 -> None

Finding a Node

Search for a node with a specific value.

def find_node(head, target_val):
    """Finds and returns the node with the target value, or None if not found."""
    current = head
    while current:
        if current.val == target_val:
            return current  # Found it!
        current = current.next
    return None # Reached the end of the list without finding it
found_node = find_node(my_list_head, 30)
if found_node:
    print(f"Found node with value: {found_node.val}")
else:
    print("Value not found.")
# Expected Output: Found node with value: 30

Summary

Concept Python Implementation Explanation
ListNode Class class ListNode: ... A blueprint for creating node objects.
Node Data self.val Stores the value of the node.
Node Link self.next Stores a reference to the next ListNode.
End of List None The next pointer of the last node is None.
Head of List head = node1 A variable holding a reference to the first node.
Helper Function def create_linked_list(items): ... A utility to easily build a list from a standard Python list.
分享:
扫描分享到社交APP
上一篇
下一篇