在单链表中删除指定值的节点
题目
给定一个单链表和一个数val,删除链表中所有值为val的节点。例如:
1->2->3->4,删除3,结果为:
1->2->4
思路1: 用栈
def remove_node_with_val1(head, val):
stack = []
p = head
while p:
if p.val != val:
stack.append(p)
p = p.next
head = None
while stack:
p = stack.pop()
p.next = head
head = p
return head
思路2: 直接操作链表
def remove_node_with_val2(head, val):
while head and head.val == val:
head = head.next
if not head:
return head
pre = head
cur = head.next
while cur:
if cur.val == val:
pre.next = cur.next
else:
pre = cur
cur = cur.next
return head
测试
import random
import operator
class Node():
def __init__(self, val):
self.val = val
self.next = None
def make_linklist(datas):
head, tail = None, None
for d in datas:
node = Node(d)
if not head:
head = node
tail = node
else:
tail.next = node
tail = node
return head
def dump_to_list(head):
l = []
p = head
while p:
l.append(p.val)
p = p.next
return l
def test(count, maxval, val):
datas = []
for _ in range(count):
d = random.randint(0, maxval)
datas.append(d)
head = make_linklist(datas)
l = dump_to_list(head)
print(l, 'remove', val)
head = remove_node_with_val1(head, val)
l = dump_to_list(head)
print(l)
head = make_linklist(datas)
head = remove_node_with_val2(head, val)
l = dump_to_list(head)
print(l)
while val in datas:
datas.remove(val)
print(datas)
def test1(count, maxval, val):
datas = []
for _ in range(count):
d = random.randint(0, maxval)
datas.append(d)
head = make_linklist(datas)
head = remove_node_with_val1(head, val)
l1 = dump_to_list(head)
head = make_linklist(datas)
head = remove_node_with_val2(head, val)
l2 = dump_to_list(head)
while val in datas:
datas.remove(val)
if not operator.eq(datas, l1):
raise Exception('Error 1')
if not operator.eq(datas, l2):
raise Exception('Error 2')
if __name__ == '__main__':
test(10, 5, 2)
test(10, 2, 2)
test(20, 10, 2)
test(20, 15, 2)
test1(100, 20, 2)
test1(200, 20, 2)
test1(2000, 20, 2)
结果
[3, 5, 2, 4, 0, 1, 2, 2, 5, 5] remove 2
[3, 5, 4, 0, 1, 5, 5]
[3, 5, 4, 0, 1, 5, 5]
[3, 5, 4, 0, 1, 5, 5]
[1, 1, 0, 2, 0, 1, 0, 1, 1, 2] remove 2
[1, 1, 0, 0, 1, 0, 1, 1]
[1, 1, 0, 0, 1, 0, 1, 1]
[1, 1, 0, 0, 1, 0, 1, 1]
[7, 8, 2, 7, 3, 3, 1, 0, 3, 8, 8, 9, 0, 8, 4, 5, 9, 1, 0, 1] remove 2
[7, 8, 7, 3, 3, 1, 0, 3, 8, 8, 9, 0, 8, 4, 5, 9, 1, 0, 1]
[7, 8, 7, 3, 3, 1, 0, 3, 8, 8, 9, 0, 8, 4, 5, 9, 1, 0, 1]
[7, 8, 7, 3, 3, 1, 0, 3, 8, 8, 9, 0, 8, 4, 5, 9, 1, 0, 1]
[9, 6, 11, 0, 10, 15, 14, 9, 2, 11, 8, 4, 0, 8, 8, 12, 13, 6, 7, 7] remove 2
[9, 6, 11, 0, 10, 15, 14, 9, 11, 8, 4, 0, 8, 8, 12, 13, 6, 7, 7]
[9, 6, 11, 0, 10, 15, 14, 9, 11, 8, 4, 0, 8, 8, 12, 13, 6, 7, 7]
[9, 6, 11, 0, 10, 15, 14, 9, 11, 8, 4, 0, 8, 8, 12, 13, 6, 7, 7]