Given a linked list and the node to be deleted, delete the node without accessing the head of the linked list
Intuition
This deletion is same as deleting a node from an array.
Approach
We use two pointers, pre
and node
to represent the previous and current node of the linked list, and we update the value of pre
and node
at each iteration. Finally, we delete the last node in the linked list.
Complexity
Time complexity: iterate the linked list once. $$O(n)$$
Space complexity: no extra space needed. $$O(1)$$
Code
|
|