题解 | #用递归函数和栈逆序一个栈#

用递归函数和栈逆序一个栈

http://www.nowcoder.com/practice/1de82c89cc0e43e9aa6ee8243f4dbefd

C++

#include<stack>

using namespace std;

class Solution {
public:
    stack<int> ReverseStackUsingRecursive(stack<int>& st) {
        if (st.empty()) {
            return st;
        }
        int i = process(st);
        ReverseStackUsingRecursive(st);
        st.emplace(i);
        return st;
    }
    int process(stack<int>& st) {
        int result = st.top();
        st.pop();
        if (st.empty()) {
            return result;
        }
        else {
            int last = process(st);
            st.emplace(result);
            return last;
        }
        
    }
};
int main() {
    int N;
    cin >> N;
    stack<int> st;
    int n;
    for (int i = 0; i < N; ++i) {
        cin >> n;
        st.emplace(n);
    }
    Solution sol;
    
    st = sol.ReverseStackUsingRecursive(st);
    for (int i = 0; i < N; ++i) {
        cout << st.top() << ' ';
        st.pop();
    }
    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
点赞 1 评论
分享
牛客网
牛客企业服务