Problem
要求:
只用一个栈,实现另一个栈的排序,除了变量之外不可用任何类型数据结构
Solution
#include <iostream>
#include <stack>
using namespace std;
void sortStack(stack<int> &s)
{
stack<int> news;
while (!s.empty()) {
int temp = s.top();
s.pop();
while (!news.empty() && news.top() < temp) {
s.push(news.top());
news.pop();
}
news.push(temp);
}
while (!news.empty()) {
s.push(news.top());
news.pop();
}
}
int main()
{
int a[] = {3, 4, 5, 1, 2, 1};
int i;
stack<int> s;
for (i = 0; i < 6; i++) {
s.push(a[i]);
}
cout << "before sort :" << endl;
for (i = 0; i < 6; i++) {
cout << s.top() <<endl;
s.pop();
}
for (i = 0; i < 6; i++) {
s.push(a[i]);
}
cout << "after sort : " <<endl;
sortStack(s);
for (i = 0; i < 6; i++) {
cout << s.top() << endl;
s.pop();
}
return 0;
}