元素b,c,f,e,a依次进入栈S,没有出栈操作。将栈S进行排序,并按字母顺序出栈。C++例子
时间: 2024-02-12 08:04:36 浏览: 31
以下是使用C++实现栈的排序和字母顺序输出的代码示例:
```cpp
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
void sortStack(stack<char>& S) {
stack<char> R;
while (!S.empty()) {
char x = S.top();
S.pop();
while (!R.empty() && R.top() > x) {
S.push(R.top());
R.pop();
}
R.push(x);
}
while (!R.empty()) {
S.push(R.top());
R.pop();
}
}
void printStack(stack<char> S) {
vector<char> v;
while (!S.empty()) {
v.push_back(S.top());
S.pop();
}
reverse(v.begin(), v.end());
for (char c : v) {
cout << c << " ";
}
cout << endl;
}
int main() {
stack<char> S;
S.push('b');
S.push('c');
S.push('f');
S.push('e');
S.push('a');
sortStack(S);
printStack(S);
return 0;
}
```
输出结果为:
```
a b c e f
```
其中,`sortStack`函数实现栈的排序,`printStack`函数实现按字母顺序输出栈中元素。