python实现链表

时间:2024-04-08 11:45:32
class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None
        
class LinkedList:
    def __init__(self):
        self.head = None
    
    def append(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
        else:
            current = self.head
            while current.next is not None:
                current = current.next
            current.next = new_node
    
    def display(self):
        current = self.head
        while current is not None:
            print(current.data, end=" ")
            current = current.next
 
# 使用示例
llist = LinkedList()
llist.append(1)
llist.append(2)
llist.append(3)
llist.display()  # 输出:1 2 3