python 如何准备链表,Python中准备链表的方法

原创
ithorizon 7个月前 (09-26) 阅读数 47 #Python

如何准备链表

链表是一种常见的数据结构,它是由一系列节点组成的,每个节点都包含两部分:一部分是数据,另一部分是指向下一个节点的指针,链表可以分为单向链表、双向链表和循环链表等,在Python中,我们可以使用类来定义链表节点和链表本身。

我们需要定义链表节点类,这个类应该包含数据字段和指向下一个节点的指针。

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

在这个类中,data字段用于存储节点的数据,next字段用于指向下一个节点。

我们需要定义链表类,这个类应该包含一些方法来操作链表,例如添加节点、删除节点和遍历链表等。

class LinkedList:
    def __init__(self):
        self.head = None
    def add_node(self, data):
        new_node = ListNode(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 remove_node(self, data):
        current = self.head
        if current and current.data == data:
            self.head = current.next
            current = None
            return True
        else:
            prev = None
            current = self.head
            while current and current.data != data:
                prev = current
                current = current.next
            if current:
                prev.next = current.next
                current = None
                return True
            else:
                return False
    
    def traverse(self):
        current = self.head
        while current:
            print(current.data)
            current = current.next

在这个类中,head字段表示链表的头节点,add_node方法用于添加节点,remove_node方法用于删除节点,traverse方法用于遍历链表并打印每个节点的数据。

我们可以使用这些类来创建和操作链表了。

创建链表
linked_list = LinkedList()
添加节点
linked_list.add_node(1)
linked_list.add_node(2)
linked_list.add_node(3)
删除节点
linked_list.remove_node(2)
遍历链表
linked_list.traverse()  # 输出 1 3


热门