Q:Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.
A: 再利用另外一个栈来模拟插入排序。 sin是原来的栈,sout是用来储存排序后的栈,
将sin.top() 元素保存在一个临时变量tmp里面,同sout中的元素比较,如果大于sout的top元素,那么就压入当前位置,否则将sout的top元素压入sin之中,tmp继续与sout的top比较,直到sout为空。
#include <iostream>
#include <stack>
using namespace std;
stack<int> sortStack(stack<int> s) {
stack<int> t;
if (s.empty()) {
return t;
}
t.push(s.top());
s.pop();
while (!s.empty()) {
int tmp = s.top();
s.pop();
while (!t.empty() && t.top() > tmp) {
s.push(t.top());
t.pop();
}
t.push(tmp);
}
return t;
}
int main() {
int a[5] = {3,5,2,4,1};
stack<int> s;
for (int i = 0; i < 5; i++) {
s.push(a[i]);
}
while (!s.empty()) {
cout<<s.top()<<" ";
s.pop();
}
cout<<endl;
for (int i = 0; i < 5; i++) {
s.push(a[i]);
}
s = sortStack(s);
while (!s.empty()) {
cout<<s.top()<<" ";
s.pop();
}
cout<<endl;
return 0;
}
本文介绍了一种通过创建两个栈来实现堆排序的方法。首先,将原始栈的顶元素暂存,然后与当前栈顶元素进行比较,将较小元素弹出并重新压入栈中,直至当前栈为空。此过程不断重复,最终实现原始栈内元素的有序排列。

被折叠的 条评论
为什么被折叠?



