Delete Node in a Linked List - Solution
Solutions and explanations
Video Explanation
We need to delete a given node, but we don't have access to its previous node or the head of the list.
This means we can't remove the node directly.
Instead, we can copy the data from the next node into the current node and unlink the next node, effectively deleting it.
Note: This approach only works if the given node is not the tail, because it relies on accessing the next node to copy its data.
# 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 # Copy next node's value
node.next = node.next.next # Skip next node
# Python's garbage collector (GC) automatically frees memory of the skipped node
Complexity Analysis
- Time Complexity:
O(1) - Space Complexity:
O(1)