给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
LeetCode链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, head: ListNode, val: int) -> ListNode:
now = head
last = None
while now is not None and now.val != val:
last = now
now = now.next
if now is None:
return None
if last is None:
head = head.next
return head