python 正规单向链表写法,定义节点类,定义链表类
#定义节点类 class list_node(): def __init__(self,value,next_node=None): self.value = value self.next_node = next_node #定义单向链表类 class link_list(): def __init__(self,node): self.head = node self.length = 1 def insert(self,next_,current): node = self.head temp = list_node(next_) for i in range(self.length): if node.value == current: if node.next_node: temp.next_node = node.next_node node.next_node = temp self.length += 1 break else: node = node.next_node continue def delete(self,value): if self.length == 1: if self.head.value == value: self.head.value = None self.length = 0 if self.length > 1: current = self.head next_ = current.next_node if current.value == value: self.head = next_ self.length -= 1 else: for i in range(self.length-1): if next_.value == value: if next_.next_node: current.next_node = next_.next_node next_ = current.next_node else: current.next_node = None self.length -= 1 else: current = next_ next_ = current.next_node def print(self): result = '' if self.length > 0: current = self.head for i in range(self.length): result = result + str(current.value)+ ' ' current = current.next_node print(result) while True: try: numbers = list(map(int,input().split())) #创建头节点 head = list_node(numbers[1]) #用头节点创建一个链表 l_list = link_list(head) #插入节点 for i in range(2,numbers[0]*2,2): l_list.insert(numbers[i], numbers[i+1]) #删除节点 l_list.delete(numbers[-1]) #打印链表 l_list.print() except: break