【发布时间】:2023-04-11 06:16:01
【问题描述】:
我很想知道如何使用 recursion 以 升序 顺序对堆栈进行排序
我已经使用递归按降序对堆栈进行了排序,但找不到升序的逻辑。
请告诉我一些逻辑。
提前致谢
编辑:
我的排序函数和插入函数的代码,用于对堆栈进行降序排序
void sort(stack<int>&st)
{
if(st.size()==1)
return;
int ele=st.top();
st.pop();
sort(st);
insert(st,ele);
return;
}
void insert(stack<int>&st,int ele)
{
int x=st.size(),y=st.top();
if(x==0||y<=ele)
{
st.push(ele);
return;
}
int t=st.top();
st.pop();
insert(st,ele);
st.push(t);
return;
}
【问题讨论】:
-
降序的解决方案是什么?
-
@Manuel 请从下面给出的链接中查看我的排序功能和插入功能。我是 stackoverflow 的新手。结果我没有在评论部分给出我的代码。请从此链接查看:paste.ubuntu.com/p/6rZghhVpnv
-
是的,不应该出现在评论中,应该出现在问题中。反正你不能把
<=改成>=吗? -
@manuel 如果我将 = ,它将终止而不在输出中显示任何内容。
-
那么您的降序代码可能也不正确。