700584. Delete Alternate Nodes
Easy
Delete Alternate Nodes
Slug: delete-alternate-nodes Difficulty: Easy Id: 700584 Topic Tags: Linked List, Data Structures Company Tags: Morgan Stanley
Summary
The problem involves deleting alternate nodes from a singly linked list. The goal is to remove every other node starting from the first node until only one node remains. This operation requires careful manipulation of the linked list's pointers to achieve the desired outcome.
Detailed Explanation
To solve this problem, we'll follow these steps:
- Initialize two pointers,
currentandprev, pointing to the head of the linked list. - Iterate through the linked list until only one node remains:
- For each iteration, check if
currentis an odd-numbered node (i.e., its index is 1 modulo 2). - If it is, skip this node by updating
prevto point to the next node (current->next) and movecurrentto that new node. - If not, update
prevto point to the current node and movecurrentone step forward.
- For each iteration, check if
- Repeat step 2 until only one node remains.
Here's a diagram illustrating the process:
1 -> 2 -> 3 -> 4 -> 5
^ ^
| |
prev current
v v
(skip) 2 -> 4
^ ^
| |
prev current
v v
(skip) 4
^ ^
| |
prev current
v v
(stop)
The time complexity of this algorithm is O(n), where n is the number of nodes in the linked list, since we visit each node once. The space complexity is O(1) as we only use a few extra variables to store pointers.
Optimized Solutions
Java
public Node deleteAlternateNodes(Node head) {
Node current = head;
Node prev = null;
while (current != null && current.next != null) {
if ((int) Math.floor((double) 1 / 2) == 0) { // check for odd-numbered node
prev = current;
current = current.next;
} else {
prev = current;
current = current.next;
prev.next = current; // skip this node
}
}
return prev != null ? prev : current;
}