当前位置:首页 > 行业动态 > 正文

python如何实现链表

链表是一种线性数据结构,其中的元素通过指针链接在一起,在Python中,我们可以使用类来实现链表,以下是一个简单的链表实现:

1、定义节点类(Node):

python如何实现链表  第1张

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

2、定义链表类(LinkedList):

class LinkedList:
    def __init__(self):
        self.head = None
    # 添加元素到链表末尾
    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
            return
        last_node = self.head
        while last_node.next:
            last_node = last_node.next
        last_node.next = new_node
    # 打印链表元素
    def print_list(self):
        cur_node = self.head
        while cur_node:
            print(cur_node.data, end=" > ")
            cur_node = cur_node.next
        print("None")

3、使用链表类:

python如何实现链表  第2张

创建一个链表对象
linked_list = LinkedList()
向链表中添加元素
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
打印链表元素
linked_list.print_list()

输出结果:

1 > 2 > 3 > None
0