C語言實現顛倒棧的方法
更新時間:2014年09月17日 11:21:58 投稿:shichen2014
這篇文章主要介紹了C語言實現顛倒棧的方法,是針對數據結構中棧的常見操作技巧,需要的朋友可以參考下
本文實例講述了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程序算法設計的學習有所幫助。