Sort the given stack elements based on their modulo with K | C ++ implementation of the above approach ; Function to sort the stack using another stack based on the values of elements modulo k ; Pop out the first element ; While temporary stack is not empty ; The top of the stack modulo k is greater than ( temp & k ) or if they are equal then compare the values ; Pop from temporary stack and push it to the input stack ; Push temp in temporary of stack ; Push all the elements in the original stack to get the ascending order ; Print the sorted elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sortStack ( stack < int > & input , int k ) { stack < int > tmpStack ; while ( ! input . empty ( ) ) { int tmp = input . top ( ) ; input . pop ( ) ; while ( ! tmpStack . empty ( ) ) { int tmpStackMod = tmpStack . top ( ) % k ; int tmpMod = tmp % k ; if ( ( tmpStackMod > tmpMod ) || ( tmpStackMod == tmpMod && tmpStack . top ( ) > tmp ) ) { input . push ( tmpStack . top ( ) ) ; tmpStack . pop ( ) ; } else break ; } tmpStack . push ( tmp ) ; } while ( ! tmpStack . empty ( ) ) { input . push ( tmpStack . top ( ) ) ; tmpStack . pop ( ) ; } while ( ! input . empty ( ) ) { cout << input . top ( ) << " ▁ " ; input . pop ( ) ; } } int main ( ) { stack < int > input ; input . push ( 10 ) ; input . push ( 3 ) ; input . push ( 2 ) ; input . push ( 6 ) ; input . push ( 12 ) ; int k = 4 ; sortStack ( input , k ) ; return 0 ; }