颠倒栈中元素--栈的逆置

来源:互联网 发布:大学生衣服淘宝店铺 编辑:程序博客网 时间:2024/06/06 00:27

思路:

1.使用递归pop出栈中元素,直到栈中元素只剩下一个元素

2.当前第一次递归返回的时候,栈中有2个元素,我们再利用另一个递归函数putItem把两个元素逆置

3.以此递归下去,直到栈中元素全部逆置。

过程如下

1)1 , 2, 3, 4 第一个递归不断出栈,第一次满足返回条件时,栈中元素只有 1

2)回到第一个递归的上一层,利用putItem把 2 压入栈中,当putItem返回时,栈中元素为 2 1

3)继续回到第一个递归的上一层,利用putItem把 3 压入栈中,当putItem返回时,栈中元素为 3 2 1

4)继续回到第一个递归的上一层,利用putItem把 4 压入栈中,当putItem返回时,栈中元素为 4 3 2 1

5)至此递归结束

#include <iostream>#include <stack>using namespace std;stack<int> st;void putItem(stack<int> &st, int data){if (st.size() == 0){st.push(data);return;}int tmp = st.top();st.pop();putItem(st, data);st.push(tmp);}void reverseStack(stack<int> &st){if (st.size() == 1){return ;}int tmp = st.top();st.pop();reverseStack(st);putItem(st, tmp);}int main(){st.push(1);st.push(2);st.push(3);reverseStack(st);while(!st.empty()){printf("%d ", st.top());st.pop();}return 0;}


 

原创粉丝点击