LeetcodeMedium- [Interview Question 18. Deleting Linked Nodes]

Given the head pointer of a one-way linked list and the value of a node to be deleted, define a function to delete the node.

Returns the head node of the deleted linked list.

Note: This question has changed from the original question

Example 1:

输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.

Example 2:

输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.

Description:

题目保证链表中节点的值互不相同
若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点

Source: LeetCode (LeetCode)
link: https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof
Copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.
Idea: traverse the linked list
directly traverse the linked list to find the correct value.
Insert picture description here

# 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:
        newhead = head
        pre = head
        while head != None:
            if head.val == val:
                if newhead == head:
                    newhead = head.next
                else:
                    pre.next = head.next
                break
            pre = head
            head = head.next            
        return newhead

Published 314 original articles · 22 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/qq_39451578/article/details/105509629