Description:
Given a stack, reverse it using recursion.
解題方法:
通過遞歸聘萨,每次將top的元素pop出來,將其加入到棧的最底層族跛。
如果加入到最低層?
通過遞歸,每層都出棧呻惕,直到棧為空。
Time Complexity:
O(n^2)
完整代碼:
void reverse(stack<int>& S) {
if(S.empty())
return;
int temp = S.top();
S.pop();
reverse(S);
addToBottom(S, temp);
}
void addToBottom(stack<int>&S, int num) {
if(S.empty())
S.push(num);
else {
int temp = S.top();
S.pop();
addToBottom(S, num);
S.push(temp);
}
}