3.6 Write the program, sort the stack in ascending order (that is, the largest element is at the top of the stack). You can use up to one additional stack to hold temporary data, but you must not copy elements into other data structures (such as arrays). The stack supports the following operations: Push, pop, Peek, and IsEmpty.
Answer
Use an additional stack to simulate the insertion sort. The data in the original stack is compared to the stack top element in the stack, and if the additional stack is empty, the data is pushed directly to the stack. Otherwise, if the stack top element of the additional stack is smaller than the element popped from the original stack, the stack top element of the additional stack is pressed into the original stack. Keep looking like this until the additional stack is empty or the top of the stack element is already greater than the element, the element is pressed into the additional stack.
C + + Implementation code:
#include <iostream>#include<stack>using namespacestd;voidStacksort (stack<int> &St) {Stack<int>T; while(!St.empty ()) { intData=St.top (); St.pop (); while(!t.empty () &&t.top () <data) {St.push (T.top ()); T.pop (); } t.push (data); } while(!T.empty ()) {St.push (T.top ()); T.pop (); }}intMain () {stack<int>St; intarr[Ten]={2,4,6,1,3,5,7,8,9,0}; for(intI=0;i<Ten; i++) St.push (Arr[i]); Stacksort (ST); while(!St.empty ()) {cout<<st.top () <<" "; St.pop (); } cout<<Endl;}
careercup-Stack and queue 3.6