Write a program to sort a stack in ascending order. You should not make any assump-
tions about how the stack is implemented. The following are the only functions that
should be used to write this program: push | pop | peek | isEmpty.
#include <iostream>
using namespace std;
Stack sort(Stack s)
{
Stack r;
while (!s.isEmpty())
{
int tmp = s.pop();
while (!r.isEmpty() && r.peek() > tmp)
{
s.push(r.pop());
}
r.push(tmp);
}
}辅助栈r中一定是倒序的,
本文介绍了一种使用辅助栈实现的栈排序算法,该算法能够将输入栈中的元素按升序排列。通过不断比较并调整两个栈的状态来完成排序过程。
142

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



