左神 程序员代码面试指南 第一章存疑处
第一章,第三个问题:用递归实现栈的逆序。
怀疑书上的代码,函数参数应为引用,而不是值传递。
原代码:
public class ReverseStack {
//在不改变栈中元素顺序情况下,获取当前栈中栈底元素
public static int getAndRemoveLastElement(Stack<Integer> stack) {
int result = stack.pop();
if(stack.isEmpty()) {
return result;
} else {
int last = getAndRemoveLastElement(stack);
stack.push(result);
return last;
}
}
//逆序一个栈
public static void reverse(Stack<Integer> stack) {
if(stack.isEmpty()) {
return;
}
int i = getAndRemoveLastElement(stack);
reverse(stack);
stack.push(i);
}
}
我认为对的代码:
class stack_reverse{ 6 7 public: 8 static int getAndRemoveLastElement(stack<int> &S){ 9 int result = S.top(); 10 S.pop(); 11 if(S.empty()){ 12 return result; 13 }else{ 14 int last = getAndRemoveLastElement(S); 15 S.push(result); 16 return last; 17 } 18 19 } 20 static void reverse(stack<int> &S){ 21 22 if(S.empty()) 23 return; 24 else{ 25 int last = getAndRemoveLastElement(S); 26 reverse(S); 27 S.push(last); 28 } 29 } 30 };