700006. Reverse alternate nodes in Link List

Medium

Reverse Alternate Nodes in Link List

Slug: given-a-linked-list-reverse-alternate-nodes-and-append-at-the-end

Difficulty: Medium

Id: 700006

Topic Tags: Linked List, Data Structures

Company Tags: Amazon, Walmart

Summary

Given a linked list, reverse alternate nodes and append the remaining nodes at the end. This problem requires manipulating a linked list by reversing every other node.

Detailed Explanation

To solve this problem, we'll first create a new head for the reversed list. Then, we'll iterate through the original list, reversing every other node. For each reversed node, we'll update the next pointer to point to the current node in the original list. Finally, we'll append the remaining nodes at the end.

Here's the step-by-step breakdown:

  1. Initialize a new head for the reversed list (let's call it reversedHead).
  2. Set currentNode to the head of the original list.
  3. Iterate through the original list until currentNode is null:
    • If currentNode is at an even index, reverse its next node and update next pointer.
    • If currentNode is at an odd index, move to the next node in the original list.
  4. When the loop finishes, append the remaining nodes (if any) at the end of the reversed list.

Time complexity: O(n), where n is the number of nodes in the linked list. Space complexity: O(1), as we only use a constant amount of space to store temporary pointers.

Optimized Solutions

Java

View on GeeksforGeeks
public class ListNode {
    int val;
    ListNode next;
    public ListNode(int x) { val = x; }
}

public static ListNode reverseAlternateNodes(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }

    ListNode reversedHead = new ListNode(0);
    ListNode currentReversedNode = reversedHead;
    ListNode currentOriginalNode = head;

    while (currentOriginalNode != null && currentOriginalNode.next != null) {
        currentReversedNode.next = new ListNode(currentOriginalNode.val);
        currentReversedNode = currentReversedNode.next;

        if (currentOriginalNode.val % 2 == 0) {
            currentOriginalNode = currentOriginalNode.next;
        } else {
            currentOriginalNode = currentOriginalNode.next.next;
        }
    }

    // Append remaining nodes
    while (currentOriginalNode != null) {
        currentReversedNode.next = new ListNode(currentOriginalNode.val);
        currentReversedNode = currentReversedNode.next;
        currentOriginalNode = currentOriginalNode.next;
    }

    return reversedHead.next;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.