Overview
Swap operations exchange the positions of the first two elements at the top of a stack. These are the simplest operations in Push Swap and are commonly used to make quick adjustments when elements are nearly in the correct position.Available Operations
sa
Swap the first 2 elements of stack A
sb
Swap the first 2 elements of stack B
ss
Execute sa and sb simultaneously
How It Works
The swap operation takes the first two elements of a stack and exchanges their positions:If the stack has fewer than 2 elements, the swap operation does nothing.
Implementation
The swap operations are implemented inft_swap.c. Here’s the core implementation:
Core Swap Function
ft_swap.c
- Checks if there are at least 2 elements in the stack
- Updates the stack head pointer to point to the second element
- Adjusts the doubly-linked list pointers to swap positions
- Maintains proper
prevandnextrelationships
Public Operation Functions
- sa
- sb
- ss
ft_swap.c
Usage Examples
Example 1: Correcting Top Two Elements
When the top two elements of stack A are in the wrong order:Example 2: Simultaneous Swap
When both stacks need their top elements swapped:Example 3: Edge Case - Single Element
When to Use
Swap operations are most effective when:- The top two elements are in the wrong order but close to their target positions
- Finalizing an almost-sorted stack
- Making minor adjustments after rotation operations
- Combining with other operations in optimization strategies
Time Complexity
- Time Complexity: O(1) - constant time operation
- Space Complexity: O(1) - no additional space required
See Also
Push Operations
Move elements between stacks
Rotate Operations
Shift all elements up by one position