class Node: def __init__(self,value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def add_front(self,value): new_node = Node(value) new_node.next = self.head self.head = new_node def add_back(self,value): new_node = Node(value) 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 print_list(self): current = self.head while current is not None: print(current.value) current = current.next list1 = LinkedList() list1.add_front(1) list1.add_front(2) list1.add_back(3) list1.print_list()
1。節點類別:
2。鍊錶類:
3。 add_front 方法:
4。 add_back方法:
5。 print_list 方法:
6。用法範例:
以上是如何在 Python 中實作單向鍊錶的詳細內容。更多資訊請關注PHP中文網其他相關文章!