Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Given linked list – head = [4,5,1,9], which looks like following:
编写一个函数来删除单链表中的节点(尾部除外),只允许访问该节点。 鉴于链表 - head = [4,5,1,9],如下所示:
4 -> 5 -> 1 -> 9 **Example 1:**
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. 说明:您将获得值为1的第三个节点,即链接列表 在调用你的函数后应该变成4 - > 5 - > 9。
Note: The linked list will have at least two elements. All of the nodes’ values will be unique. The given node will not be the tail and it will always be a valid node of the linked list. Do not return anything from your function.
链表至少有两个元素。 所有节点的值都是唯一的。 给定节点不是尾部,它始终是链表的有效节点。 不要从你的功能中返回任何东西。
思路: 考察链表结点的删除操作。 从头至尾遍历,直到找到相符的节点。 此思路行不通,因为只给出了当前节点,借鉴网上思想。 https://blog.csdn.net/coder_orz/article/details/51398604
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
p = node
p.val = p.next.val
p.next = p.next.next
if __name__ == "__main__":
l = ListNode(4)
l.next = ListNode(5)
l.next.next = ListNode(1)
l.next.next.next = ListNode(9)
Solution().deleteNode(ListNode(5))