C++_homework_StackSort
生活随笔
收集整理的這篇文章主要介紹了
C++_homework_StackSort
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
顧名思義(?)類似于單調棧?維護一個單調遞減的棧。一旦準備入棧的元素大于棧頂元素,棧一直彈出直到準備入棧的元素小于等于棧頂元素,彈出的元素壓入另一個tmp棧中。
#include <iostream>
#include <stack>
#include <cstdlib>
#include <ctime>
using namespace std; void StackSort(stack<int>& s)
{
stack<int> tmp;
while(!s.empty()){
tmp.push(s.top());
s.pop();
}
while(!tmp.empty()){
if(s.empty()){s.push(tmp.top());tmp.pop();}
else{
int x=tmp.top();
tmp.pop();
if(x<=s.top()) s.push(x);
else{
while(!s.empty()&&x>s.top()){
tmp.push(s.top());
s.pop();
}
s.push(x);
}
}
}
} 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{};
srand((unsigned)time());
stack<int> s;
for (int i{};i<n;i++) s.push(rand()%);
cout<<"Before sorting:"<<endl<<endl; display(s);
cout<<"After sorting:"<<endl; StackSort(s); display(s);
return ;
}
s:
tmp: 8 7 9
s: 9
tmp: 8 7
s: 9 7
tmp: 8
s: 9 8
tmp: 7
s: 9 8 7
tmp:
總結
以上是生活随笔為你收集整理的C++_homework_StackSort的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql中mysql数据库丢失报错Ca
- 下一篇: TOYS POJ 2318 计算几何 叉