【发布时间】:2015-05-21 20:08:18
【问题描述】:
所以我写了这段代码来确定一个表达式在堆栈中是否有平衡括号:
public static boolean isBalanced(String expr) {
StringStack stack = new StringStackRefBased();
try{
for (int i = 0; i<expr.length(); i++){
if (expr.charAt(i) == ('(')){
stack.push("(");
} else if (expr.charAt(i) == (')')){
stack.pop();
}
}
if (stack.isEmpty()){
return true;
} else {
return false;
}
} catch (StringStackException e) {
return false;
}
}
问题是,即使表达式有平衡括号,堆栈也会继续返回 false,所以我的代码有什么问题?
这是 StringStackRefBased 的代码
public class StringStackRefBased implements StringStack {
private StringNode head;
public boolean isEmpty(){
return head == null;
}
public void push(String item) throws StringStackException{
head = new StringNode(item);
}
public String pop() throws StringStackException{
String result = null;
if(isEmpty()){
throw new StringStackException("Empty Stack");
}
head.next = head;
return head.toString();
}
public String peek() throws StringStackException{
if (isEmpty()){
throw new StringStackException("Stack underflow");
}
return head.toString();
}
}
【问题讨论】:
-
好吧,StringStack 里面没有太多东西,但是 StringStackRefBased 里面有所有的方法。我更新了代码以显示 StringStackRefBased。我最想知道的是,push 和 pop 方法是否正确?
-
为什么不只使用一个 int 并执行
count++和count--?然后最后你可以检查计数是否为零。 -
问题在于你的
StringStack,因为如果我用Java内置的Stack替换它,它就可以正常工作了。 -
验证推送方式。我认为问题本身就存在。
-
您对
isEmpty()的实现与您对push()和pop()的实现不兼容。在调用push()之后,无论你调用了多少次pop,head 都不会是null