1. SortUsingStackOnly.cpp
Write a function StackSort to sort a stack in ascending order.
The following are the only functions that should be
used to write this function: push | pop | top | empty.
void StackSort(stack<int>& s);
Write a function StackSort to sort a stack in ascending order.
The following are the only functions that should be
used to write this function: push | pop | top | empty.
void StackSort(stack<int>& s);
PostCondition: sorted stack with minimum on the top
作业要求大致是用一个栈实现升序排列,具体过程用一个变量存储栈顶元素,然后两个栈互相倒元素,直至找到满足条件的位置插入即可。
srand():srand和rand()配合使用产生伪随机数序列。rand函数在产生随机数前,需要系统提供的生成伪随机数序列的种子,rand根据这个种子的值产生一系列随机数。如果系统提供的种子没有变化,每次调用rand函数生成的伪随机数序列都是一样的。
#include <bits/stdc++.h> #include <cstdlib> #include <ctime> using namespace std; void StackSort(stack<int>& s) { stack<int> Q; int t; t=s.top(); s.pop(); Q.push(t); while(!s.empty()) { t=s.top();//取出栈顶元素 s.pop(); int cnt=0; while(t<Q.top())//如果不能放入则将栈中元素弹出 { s.push(Q.top()); Q.pop(); cnt++;//记录弹出个数 if(Q.empty())break; } Q.push(t); while(cnt--) { Q.push(s.top()); s.pop();//依次放回 } } int len=Q.size(); while(len--) { s.push(Q.top()); Q.pop(); } } void display(stack<int> s) { while (!s.empty()) cout<<s.top()<<endl,s.pop(); cout<<endl; } int main(int argc,char**argv) { const int n{20}; srand((unsigned)time(0));//用time作为rand()函数的种子 stack<int> s; for (int i{0}; i<n; i++) s.push(rand()%100);//获得100内随机数 cout<<"Before sorting:"<<endl<<endl; display(s); cout<<"After sorting:"<<endl; StackSort(s); display(s); return 0; }