编写程序,按升序对栈进行排序(即最大元素位于栈顶)。最多允许使用一个额外的栈存放临时数据,但不准将数据复制到别的数据结构(如数组)中。该栈支持如下操作:pop,push,peek / top,和isEmpty。
下面的代码直接使用C++ STL stack实现。
思路比较简单:每次都取主栈中相邻两元素进行比较,将其中较大元素放进子栈相应位置。
#include <bits/stdc++.h> // two stack to implement stackSort
using namespace std;
void insertStack(int val, stack<int>& hostStack, stack<int>& subStack) {
if (!subStack.empty()) {
int subTop = subStack.top();
while (val > subTop) {
hostStack.push(subTop);
subStack.pop();
if (subStack.empty()) {
break;
}
subTop = subStack.top();
}
}
subStack.push(val);
}
void stackSort(stack<int>& hostStack) {
stack<int> subStack;
while (!hostStack.empty()) {
int front = hostStack.top();
hostStack.pop();
if (hostStack.empty()) {
hostStack.push(front);
break;
}
int next = hostStack.top();
if (front >= next) {
insertStack(front, hostStack, subStack);
} else {
hostStack.pop();
insertStack(next, hostStack, subStack);
hostStack.push(front);
}
}
while (!subStack.empty()) {
hostStack.push(subStack.top());
subStack.pop();
}
}
int main(int argc, char const *argv[]) {
stack<int> hostStack;
int n;
cout << "how many elements to push into hostStack : \n";
cin >> n;
while (n--) {
int tmp;
cin >> tmp;
hostStack.push(tmp);
}
stackSort(hostStack);
cout << "after sort : \n";
while (!hostStack.empty()) {
cout << hostStack.top() << " ";
hostStack.pop();
}
cout << endl;
return 0;
}