题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
import sys
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def insert(head, val1, val2):
cur = head
while cur:
preNext = cur.next
if cur.val == val2:
cur.next = ListNode(val1)
cur.next.next = preNext
break
else:
cur = cur.next
return head
def delete(head, val):
dummy_head = ListNode(val = None)
dummy_head.next = head
cur = dummy_head
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
break
else:
cur = cur.next
return dummy_head.next
lis = list(map(int,sys.stdin.readline().strip().split()))
n = lis[0]
head = lis[1]
node = lis[2:-1]
deleted = lis[-1]
head = ListNode(head)
left, right = 0, 1
while right < len(node):
insert(head, node[left], node[right])
left += 2
right += 2
delete(head, deleted)
ans = []
cur = head
while cur:
ans.append(str(cur.val))
cur = cur.next
print(' '.join(ans))
需要比较的是node的值是不是要找的val,一定是node.val == val1 而不是node==val1,一个节点是不会等于一个值的!