//非遞歸實現。
#include <iostream>
#include <stack>
using namespace std;
void Deal(stack<int> &st,int val)
{
stack<int> temp;
while(st.empty()==false)
{
temp.push(st.top());
st.pop();
}
st.push(val);
while(temp.empty()==false)
{
st.push(temp.top());
temp.pop();
}
}
void Printf(stack<int> st)
{
while(st.empty()==false)
{
cout<<st.top()<<" ";
st.pop();
}
cout<<endl;
}
int main()
{
stack<int> st;
for(int i=0;i<5;i++)
{
Deal(st,i);
}
Printf(st);
return 0;
}
//遞歸實現。
#include <iostream>
#include <stack>
using namespace std;
void Deal(stack<int> &st,int val)
{
if(st.empty()==true)
{
st.push(val);
return;
}
int temp = st.top();
st.pop();
Deal(st,val);
st.push(temp);
}
void Printf(stack<int> st)
{
while(st.empty()==false)
{
cout<<st.top()<<" ";
st.pop();
}
cout<<endl;
}
int main()
{
stack<int> st;
for(int i=0;i<5;i++)
{
Deal(st,i);
}
Printf(st);
return 0;
}
筆試題:逆序一個棧的遞歸與非遞歸實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.