题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
class ListNode: def __init__(self, val): self.val = val self.next = None class LinkList: def __init__(self): self.head = ListNode(0) def is_empty(self): return self.head is None #循环创建链表 def create_linklist(self, nodes): for node in nodes: cur = self.head tmp = ListNode(node[0]) while cur:#在插入节点时分两种情况,尾节点为空或不为空 if cur.val == node[1] and cur.next: tmp.next = cur.next cur.next = tmp break elif cur.val == node[1] and not cur.next: cur.next = tmp break cur = cur.next def delete(self, value): cur = self.head if self.is_empty(): return elif self.head.val == value and self.head.next: pre = self.head self.head = self.head.next pre.next = None return elif self.head.val == value and not self.head.next: self.head = None return elif not self.head.next: return else: while cur.next: if cur.next.val == value and cur.next.next: cur.next = cur.next.next elif cur.next.val == value and not cur.next.next: cur.next = None cur = cur.next def print_linklist(self): cur = self.head if not cur: print(None) nodes = [] while cur: nodes.append(str(cur.val)) cur = cur.next print(" ".join(nodes)) ll = LinkList() lt = list(map(int, input().split())) nodn, headval, delval = lt[0], lt[1], lt[-1] nodes = [] for i in range(2, len(lt) - 1, 2): nodes.append((lt[i], lt[i + 1])) ll.head.val = headval ll.create_linklist(nodes) ll.delete(delval) ll.print_linklist()