我对这个问题的解决方法是当递归使用堆栈进行工作时,因此如果我的输入是n个数字,递归将为我提供从1到n的堆栈反转,并添加第0个元素,我将首先复制堆栈(说S1)进入一个空堆栈(说S2),将第0个元素压入S1,然后将元素从堆栈S2复制回S1。这是我的代码,我无法解决实现我的方法的问题。
void reverseStack(stack<int> &input, stack<int> &extra) {
if(input.size()==0)
{
return;
}
int x=input.top();
input.pop();
reverseStack(input,extra);
for(int i=0;i<input.size();i++)
{
extra.push(input.top());
input.pop();
}
input.push(x);
for(int i=0;i<extra.size();i++)
{
input.push(extra.top());
extra.pop();
}
}
答案 0 :(得分:1)
由于堆栈是先进先出(FILO)数据结构,因此可以通过反复移除顶部元素并将其推入另一个堆栈来实现堆栈的反转。最后,只需将原始堆栈换成相反的堆栈即可。使用move
语义可以避免任何深层复制。
template<typename T>
void reverse(std::stack<T> &the_stack)
{
std::stack<T> reverse_stack;
while(!the_stack.empty()) {
reverse_stack.push(std::move(the_stack.top()));
the_stack.pop();
}
the_stack = std::move(reverse_stack);
}
这不使用递归,但是任何迭代程序都可以重新构造为递归程序,例如
template<typename T>
void reverse_recursive(std::stack<T> &the_stack,
std::stack<T> &reverse_stack)
{
if(!the_stack.empty()) {
reverse_stack.push(std::move(the_stack.top()));
the_stack.pop();
reverse_recursive(the_stack,reverse_stack);
} else
the_stack = std::move(reverse_stack);
}
template<typename T>
void reverse(std::stack<T> &the_stack)
{
std::stack<T> auxiliary_stack;
reverse_recursive(the_stack,auxiliary_stack);
}
比简单的迭代解决方案要复杂得多。
答案 1 :(得分:1)
您应该为输入和额外的堆栈声明大小变量。
void reverseStack(stack<int> &input, stack<int> &extra) {
// Write your code here
if(input.size()==0)
{
return;
}
int x=input.top();
input.pop();
reverseStack(input,extra);
int size1 = input.size();
for(int i=0;i<size1;i++)
{
extra.push(input.top());
input.pop();
}
input.push(x);
int size2 = extra.size();
for(int i=0;i<size2;i++)
{
input.push(extra.top());
extra.pop();
}
}
答案 2 :(得分:0)
#include <stack>
void rev2(stack<int> &s, stack<int> &s2){
if(s.empty()){
return;
}
int x = s.top();
s.pop();
rev2(s,s2);
s2.push(x);
}
void reverseStack(stack<int> &s, stack<int> &s2) {
// Write your code here
rev2(s,s2);
int size = s2.size();
for(int i=0;i<size;i++){
s.push(s2.top());
s2.pop();
}
}
答案 3 :(得分:0)
void reverseStack(stack<int> &input, stack<int> &extra) {
if(input.empty())
{
return;
}
int x = input.top();
input.pop();
reverseStack(input,extra);
while(!input.empty())
{
extra.push(input.top());
input.pop();
}
input.push(x);
while(!extra.empty())
{
input.push(extra.top());
extra.pop();
}
}