No237. Delete the node in the linked list
topic
Please write a function to delete a given (non-end) node in a linked list. The only parameter passed into the function is the node to be deleted.
There is a linked list – head = [4,5,1,9], which can be expressed as:
Example 1
- Input: head = [4,5,1,9], node = 5
- Output: [4,1,9]
- Explanation: Given the second node with a value of 5 in your linked list, after calling your function, the linked list should become 4 -> 1 -> 9.
Example 2
- Input: head = [4,5,1,9], node = 1
- Output: [4,5,9]
- Explanation: Given the third node in your linked list whose value is 1, then after calling your function, the linked list should become 4 -> 5 -> 9.
prompt
- The linked list contains at least two nodes.
- The values of all nodes in the linked list are unique.
- The given node is not the end node and must be a valid node in the linked list.
- Don't return any results from your function.
Ideas
Perform assignment and pointer operations
Problem-solving code (Python3)
class Solution:
def deleteNode(self, node):
#链表至少包含两个结点且有效结点
node.val,node.next = node.next.val,node.next.next
Complexity analysis:
- Time complexity O(1)
- Space complexity O(1)