(Python) algorithm dog dishes diary (list series) _leetcode 237. delete the list of nodes

Please write a function that makes it possible to delete a list given (non-end) node, you will only be required for a given node is removed.

A list of existing - head = [4,5,1,9], it can be expressed as:

Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
After a given second node in the list you value of 5, then call your function: Dictionary the list strain 4 -> 1 -> 9.
example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
After a given value 1 of the list you third node, then call your function: Dictionary the list strain 4 -> 5 -> 9.
 

Description:

List comprising at least two nodes.
The value of all the nodes in the list are unique.
Non given node and the end node must be a valid node in the linked list.
Do not return any results from your functions.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/delete-node-in-a-linked-list
 

This question is very interesting, it has no head, only to a node

1-> 2-> 3-> 4, deleted here 2

1->3->3->4    1-.>3->4

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next

That there are head cases, do not know right

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        if head == node:
            tmp=head.next
            head.next = None
            head = tmp
        else:
            while(head.next.next):
                if head.next==node:
                    head.next= head.next.next
                else:
                    head = head.next

 

Published 44 original articles · won praise 0 · Views 1909

Guess you like

Origin blog.csdn.net/weixin_39331401/article/details/104548169