Overview
Rotate operations shift all elements in a stack upward by one position. The first element (at the top) becomes the last element (at the bottom). These operations are crucial for positioning target elements at the top of the stack for further manipulation.Available Operations
ra
Rotate stack A upward
rb
Rotate stack B upward
rr
Rotate both stacks simultaneously
How It Works
The rotate operation takes the top element and moves it to the bottom, shifting all other elements up:- Top element moves to the bottom
- All other elements shift up one position
- The second element becomes the new top
If the stack has fewer than 2 elements, the rotate operation does nothing.
Implementation
The rotate operations are implemented inft_rotate.c. Here’s the complete implementation:
Core Rotate Function
ft_rotate.c
- Validation: Check if there are at least 2 elements
- Find Last Node: Traverse to the end of the linked list
- Attach Top to Bottom: Link the current top node to the last node
- Update Stack Head: Make the second element the new top
- Fix Pointers: Update
prevandnextpointers to maintain list integrity
Public Operation Functions
- ra
- rb
- rr
ft_rotate.c
a: Pointer to stack Aprint: If false, outputs “ra” to stdout
Detailed Operation Flow
Single Stack Rotation
Simultaneous Rotation
Usage Examples
Example 1: Positioning Target Element
Bringing a specific element to the top:Example 2: Circular Processing
Scanning through all elements:Example 3: Optimized Dual Rotation
Strategic Applications
Element Positioning
Element Positioning
Rotate operations are essential for bringing elements to the top of the stack for:
- Pushing to the other stack
- Swapping with another element
- Comparing with the top of the other stack
Median-Based Sorting
Median-Based Sorting
When dividing elements around a median value:This keeps larger elements in A while moving smaller ones to B.
Final Positioning
Final Positioning
After sorting, rotate to ensure the minimum element is at the top:
Optimization with rr
Optimization with rr
When both stacks need rotation in the same direction:This minimizes total operation count.
Rotation vs. Reverse Rotation
Choosing between rotate and reverse rotate depends on the position of your target element:- Upper Half
- Lower Half
Performance Characteristics
- Time Complexity: O(n) - must traverse to find the last node
- Space Complexity: O(1) - no additional memory allocation
- Operation Count: Each rotation counts as one operation
See Also
Reverse Rotate
Shift stack elements downward
Push Operations
Transfer elements between stacks
Swap Operations
Exchange top two elements