Reverse rotate operations shift all elements in a stack downward by one position. The last element (at the bottom) becomes the first element (at the top). These operations provide an efficient way to access elements in the lower half of the stack.
Step 1: Initial StateStack A: [5] → [3] → [8] → [1] → NULL top bottomStep 2: Execute 'rra'- Traverse to find last: [1]- Find second_last: [8]Step 3: Detach Last- Set [8]->next = NULL- [1] is now isolatedStep 4: Move to Top- Set [1]->next = [5]- [1] now points to old topStep 5: Update Head- Set stack head to [1]Step 6: Final StateStack A: [1] → [5] → [3] → [8] → NULL top bottom
Choose reverse rotate over regular rotate based on element position:
Position Calculation
Visual Guide
// Pseudo-code for choosing rotation directionint target_index = find_index(stack, target_value);int stack_size = stack_len(stack);if (target_index <= stack_size / 2){ // Target is in upper half // Use regular rotate (ra/rb) while (target_index-- > 0) ra(&stack);}else{ // Target is in lower half // Use reverse rotate (rra/rrb) int rotations = stack_size - target_index; while (rotations-- > 0) rra(&stack);}
Stack with 7 elements:Position 0: [5] ← Use ra (0 rotations)Position 1: [3] ← Use ra (1 rotation)Position 2: [8] ← Use ra (2 rotations)Position 3: [1] ← Median (equal cost)Position 4: [9] ← Use rra (3 rotations)Position 5: [2] ← Use rra (2 rotations)Position 6: [7] ← Use rra (1 rotation)Rule: If index > size/2, use reverse rotate
The above_median flag in the node structure (see push_swap.h:26) is set during node initialization to indicate whether to use rotate or reverse rotate for optimal positioning.
Time Complexity: O(n) - must traverse to find the last node
Space Complexity: O(1) - no additional memory allocation
Traversal: Visits each node once to find the end
Although reverse rotate has O(n) complexity, it’s often the most efficient choice for accessing elements in the lower half of the stack. The key is minimizing the total number of operations, not the complexity of individual operations.