从链表里删除指定内容的节点
class Node: | |
def __init__(self, v, n=None): | |
self.v = v | |
self.n = n | |
def do_print(head: Node): | |
t = head | |
print('=====') | |
while t is not None: | |
print(t.v) | |
t = t.n | |
print('=====') | |
def remove_nodes_with_val(head: Node, v): | |
tmp = Node(v+1, head) | |
p = tmp | |
while p.n is not None: | |
if p.n.v == v: # remove it | |
p.n = p.n.n | |
else: | |
p = p.n | |
return tmp.n | |
if __name__ == '__main__': | |
head = Node(1, Node(2, Node(3, Node(2, Node(1))))) | |
head = remove_nodes_with_val(head, 2) | |
do_print(head) | |
head = Node(1, Node(2, Node(3, Node(2, Node(1))))) | |
head = remove_nodes_with_val(head, 1) | |
do_print(head) | |
head = Node(1, Node(2, Node(3, Node(2, Node(1))))) | |
head = remove_nodes_with_val(head, 4) | |
do_print(head) | |
do_print(None) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment