700085. Linked List in Zig-Zag fashion

Medium

Linked List in Zig-Zag fashion

Slug: linked-list-in-zig-zag-fashion

Difficulty: Medium

Topic Tags: Linked List, Data Structures

Company Tags: Amazon, OYO Rooms

Summary

Given a singly linked list and an integer n, print the elements of the linked list in zig-zag order. The order is alternating between left to right and right to left. This problem requires manipulating the linked list nodes and adjusting the pointers accordingly.

Detailed Explanation

To solve this problem, we'll use a simple algorithm that iterates through the linked list and prints the elements based on the zig-zag pattern. We'll keep track of whether we're currently printing from left to right or right to left using a boolean flag direction. When direction is true, we print from left to right, and when it's false, we print from right to left.

Here's the step-by-step breakdown:

  1. Initialize an empty stack S.
  2. Traverse the linked list.
  3. For each node:
    • If direction is true, push the current node onto S and set direction to false. This indicates we're switching from left to right to right to left.
    • Otherwise (i.e., direction is false), pop a node from S and print its value. Set direction to true.
  4. Continue this process until the linked list is fully traversed.

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 exactly once. The space complexity is O(n) as well, due to the use of a stack to store nodes.

Optimized Solutions

Java

View on GeeksforGeeks
public void printZigZag(Node head, int n) {
    boolean direction = true;
    Stack<Node> S = new Stack<>();
    Node curr = head;

    while (curr != null) {
        if (direction) {
            S.push(curr);
            direction = false;
        } else {
            System.out.println(curr.data);
            direction = true;
            curr = curr.next;
        }
    }

    while (!S.isEmpty()) {
        System.out.println(S.pop().data);
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.