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:

  1. Initialize two pointers, current and prev, pointing to the head of the linked list.
  2. Iterate through the linked list until only one node remains:
    • For each iteration, check if current is an odd-numbered node (i.e., its index is 1 modulo 2).
    • If it is, skip this node by updating prev to point to the next node (current->next) and move current to that new node.
    • If not, update prev to point to the current node and move current one step forward.
  3. 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

View on GeeksforGeeks
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;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.