题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
class Node: # 节点 def __init__(self, v): self.v = v self.next = None class SingleLinkList: def __init__(self, v): # 初始化的时候定义头部 self.head = Node(v) # 头部是一个节点,不是值 def add(self, v1, v2): """ 增加节点: 寻找到v2在它后边插入v1 :return: 修改链表 """ n = Node(v1) cur = self.head while cur: if cur.v == v2: n.next = cur.next cur.next = n break else: cur = cur.next def delete(self, v): cur = self.head pre = None while cur: if cur.v == v: if not pre: # 删除head self.head = cur.next else: # 非head pre.next = cur.next break else: pre = cur cur = cur.next def show(self): cur = self.head while cur: print(cur.v, end=" ") cur = cur.next print() if __name__ == "__main__": while True: try: cmd = list(map(int, input().split())) L = SingleLinkList(cmd[1]) lst = cmd[2:-1] for i in range(int(len(lst) / 2)): L.add(lst[2 * i], lst[2 * i + 1]) L.delete(cmd[-1]) L.show() except: break