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中文网其他相关文章!