700085. Linked List in Zig-Zag fashion
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:
- Initialize an empty stack
S. - Traverse the linked list.
- For each node:
- If
directionistrue, push the current node ontoSand setdirectiontofalse. This indicates we're switching from left to right to right to left. - Otherwise (i.e.,
directionisfalse), pop a node fromSand print its value. Setdirectiontotrue.
- If
- 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
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);
}
}