您的位置:首页 > 编程语言 > C语言/C++

C语言实现颠倒栈的方法

2014-09-17 11:21 921 查看

本文实例讲述了C语言实现颠倒栈的方法,很实用的技巧。分享给大家供大家参考之用。

具体实现方法如下:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
void initializeStack(stack<int> &st)
{
for(int i = 1; i <= 5; i++)
st.push(i);
}
void addToStack(stack<int>& st, int i)
{
if(st.empty())
st.push(i);
else {
int top = st.top();
st.pop();
addToStack(st, i);
st.push(top);
}
}
void reverseStack(stack<int> &st)
{
if(st.empty())
return;
int top = st.top();
st.pop();
reverseStack(st);
addToStack(st, top);
}
void print(stack<int> st)
{
if(st.empty())
return;
else {
int top = st.top();
st.pop();
print(st);
cout << top << " ";
}
}
void main()
{
stack<int> st;
initializeStack(st);
print(st);
cout << endl;
reverseStack(st);
print(st);
}

希望本文所述对大家C程序算法设计的学习有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C语言