如果它们的顶级元素相同,则两个堆栈是相同的,并且剩余的堆栈是相同的(即,递归条件).
现在,想一想在从方法调用返回之前要做什么,以便使堆栈与调用时给定的方式相同.
- -编辑 - -
工作的Java代码(源自Markus A.解决方案,但有趣地使用了"finally"和泛型):
static <T> boolean compareStacks(Stack<T> a, Stack<T> b) {
if (a.isEmpty() != b.isEmpty()) return false;
if (a.isEmpty() && b.isEmpty()) return true;
T element_a = a.pop();
T element_b = b.pop();
try {
if (((element_a==null) && (element_b!=null)) || (!element_a.equals(element_b)))
return false;
return compareStacks(a, b);
} finally { // restore elements
a.push(element_a);
b.push(element_b);
}
}
Run Code Online (Sandbox Code Playgroud)
在伪代码中,您可以执行以下操作:
boolean compareStacks(a, b) {
if (a.isEmpty() != b.isEmpty()) return false; // check if one is empty
if (a.isEmpty() && b.isEmpty()) return true; // check if both are empty
element_a = a.pop(); // grab elements and compare them
element_b = b.pop();
if (((element_a==null) && (element_b!=null)) || !element_a.equals(element_b)) {
a.push(element_a); // if they are not equal, restore them and return false
b.push(element_b);
return false;
}
result = compareStacks(a, b); // compare shortened stacks recursively
a.push(element_a); // restore elements
b.push(element_b);
return result; // return result from recursive call
}
Run Code Online (Sandbox Code Playgroud)