给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
示例 1:
输入: head = [4,5,1,9], val = 5 输出: [4,1,9] 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
输入: head = [4,5,1,9], val = 1 输出: [4,5,9] 解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
# 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:
# Special case: if the node to be deleted is the head node
if head and head.val == val:
return head.next
cur = head
pre = None
# Traverse the list to find the node to delete
while cur and cur.next:
if cur.next.val == val:
# Bypass the node to delete
cur.next = cur.next.next
return head
cur = cur.next
return head
当 是头节点,并且 等于要删除的值 时,需要更新头节点的引用。