- 5
- 0
- 约4.04千字
- 约 4页
- 2022-08-20 发布于四川
- 举报
使用堆栈按升序对元素进行排序,即使最小的元素成为堆栈的顶部元素。例如, 给定堆栈元素(从下到上):5, 2, 6, 9,对元素进行排序以使堆栈元素成为(从 下到上):9, 6, 5, 2O您可以使用的唯一数据结构是基于数组的堆栈。给定一 个堆栈st,使用一个额外的堆栈tmpst来存储临时数据。
a.编写一个C++程序,以升序对基于数组的堆栈中的元素进行排序。
b.演示给定输入编号{25.10, 15, 2030}的排序过程。
算法:
pop将st输出到一个变量tmp,直到它完成所有元素。而tmpst不为空如果tmpst的顶部元素小于tmp,
弹出tmpst并将该元素推送到st上将tmp推到tmpst上
核心代码:
void Solution::sort_by_stack(stackint st){ 一 一
stackint *tmpst = new stackint;
int index = 0;
//数据栈不为空
while(!st. empty()) {//获取数据栈栈顶元素
int tmp = st. top ();//栈顶元素弹出
St. pop();index++;
cout 〃\t〃 index 〃 st: pop out 〃 tmp 〃 ==〉〃 endl;//辅助栈为空,直接入栈
if(tmpst-empty ()) {tmpst-push(tmp);
cout zz\t\ttmpst : push 〃 tmp endl; continue;)
//辅助栈不为空,whiledtmpst-empty()) {
int tmpst_top = tmpst-top();
cout z,\t\ttmpst: get the top element 〃 tmpst_top endl;if (tmp tmpst_top) {
//辅助栈栈顶元素 数据栈栈顶元素//辅助栈栈顶元素出栈,压入数据栈
tmpst-pop ();cout z/\t\t\tSince 〃 tmpst_top 〃 〃 tmp
〃,tmpst : pop out 〃 tmpst_top endl;st.push(tmpst_top);
cout /z\t\t\tst: push 〃 tmpst_top endl;)
else if (tmp tmpst_top) {//辅助栈栈顶元萋 数据栈栈顶元素
//跳过当前循环,数据栈栈顶元素直接压入辅助栈
cout /z\t\t\tSince 〃 tmpst_top 〃 〃 tmp 〃,exit the loop” endl;break;
)}
//数据栈栈顶元素压入辅助栈tmpst-push(tmp);
cout /z\t\ttmpst : push 〃 tmp endl;
)
//将数据从辅助栈依次放入数据栈
while(!tmpst-empty()) {int x = tmpst-top();
tmpst-pop();st. push(x);
))
运行结果:
? F:\work\code\sortByStack.exe1St :2st:303st:4st:30205st:6st:7st:tmpst:30pop outtmpst:20pop outtmpst:15pop out8st:9st:element 15looploop10loop11tmpst:12element 2030, exit the loop(1) push the elements 25 10 15 20 30 onto the stack st.(2) the process of sorting elements of stack st is:element 3015, tmpst : pop outelement 1015, exit the loopSince 15 20, exit the loop tmpst : push 20element 10
? F:\work\code\sortByStack.exe
1
St :
2
st:
30
3
st:
4
st:
30
20
5
st:
6
st:
7
st:
tmpst:
30
pop out
tmpst:
20
pop out
tmpst:
15
pop out
8
st:
9
st:
element 15
loop
loop
10
loop
11
tmpst:
12
element 20
30, exit the loop
(1) push the elements 25 10 15 20 30 onto the stack st.
(2) the process of sorting
原创力文档

文档评论(0)