题目:用递归颠倒一个栈。例如输入栈{1, 2, 3, 4, 5},1 在栈顶。
颠倒之后的栈为{5, 4, 3, 2, 1},5 处在栈顶。
/*
66.颠倒栈。
题目:用递归颠倒一个栈。例如输入栈{1, 2, 3, 4, 5},1 在栈顶。
颠倒之后的栈为{5, 4, 3, 2, 1},5 处在栈顶。
*/
void InsertStack(stack<int> &st,int value)
{
if(st.empty())
st.push(value);
else
{
int tmp=st.top();
st.pop();
InsertStack(st,value);
st.push(tmp);
}
}
void ReverseStack(stack<int> &st)
{
if(st.empty())
return;
int tmp=st.top();
st.pop();
ReverseStack(st);
InsertStack(st,tmp);
}
void ReverseStackTest()
{
int value=0;
stack<int> st;
cout<<"input stack : "<<endl;
while(cin>>value)
st.push(value);
ReverseStack(st);
while(!st.empty())
{cout<<st.top()<<endl;st.pop();}
}