[英]Testing for Balanced Delimiters using a Stack
我根據單鏈列表創建了一個通用堆棧類,並試圖使用它來檢查用戶輸入中是否有平衡的定界符。 我正在檢查以下定界符:(){} []
堆棧碼
public class SLStack<T> {
//initializes the first node
private SLStackNode<T> head; //initializes the first node
//constructor initializes the first node as null to simulate an empty stack
public SLStack(){
head = null;
}
//inner node class
public static class SLStackNode<T>{
public T data;
public SLStackNode<T> next;
}
//adds an element to the top of the stack
public void push(T value){
SLStackNode<T> newNode = new SLStackNode<>();
newNode.data = value;
newNode.next = head;
head = newNode;
}
//removes an element from the top of the stack
public T pop(){
if (head == null){
throw new IllegalStateException("The list is empty.");
}
T value = head.data;
head = head.next;
return value;
}
//checks the element at the top of the stack
public T top(){
if (head == null){
throw new IllegalStateException("The list is empty.");
}
T value = head.data;
return value;
}
public boolean isEmpty(){
return head == null;
}
public void printStack(SLStackNode<T> node, int depth) {
if (node.next != null) {
System.out.println(depth + " : " + node.data); //recurses through the stack
//printStack(node.next);
}
System.out.println(depth + " : " + node.data); //recursive base case
}
}
余額測試儀代碼
public class Balanced {
public static void main(String[] args)
{
SLStack<ExpressionScanner.Token> delimStack = new SLStack<>();
System.out.println("Enter one expression per line.");
System.out.println("End the program with a period on a line by itself.");
ExpressionScanner escan = new ExpressionScanner(new Scanner(System.in));
while (escan.hasNext()) {
ExpressionScanner.Token token = escan.next();
if (token.getType() == ExpressionScanner.Token.Type.OP || token.getType() == ExpressionScanner.Token.Type.VAR){
//ignore these tokens
continue;
}
if (token.getType() == ExpressionScanner.Token.Type.DELIM_OPEN){
//push opening delimiter to the stack
delimStack.push(token);
}
if (token.getType() == ExpressionScanner.Token.Type.DELIM_CLOSE){
//look for matching opening delimiter in the stack and pop it from the stack
if (token == delimStack.top()){
delimStack.pop();
}else{
throw new IllegalStateException("Imbalanced delimiter detected.");
}
}
if (delimStack.isEmpty()){
System.out.println("Delimiters are balanced.");
}else{
System.out.println("Imbalanced delimiter detected.");
}
//System.out.println(token);
}
}
}
當我運行測試儀時,總是說定界符是不平衡的,無論它是什么。 即使只執行一個打開的定界符,它也會表示存在不平衡,但不會引發異常。 如果單個結束定界符或多個結束定界符,它將引發異常。 如果我有兩個打開的定界符,則不會終止。
如果有人需要,我也可以發布ExpressionScanner的代碼。
if (token == delimStack.top()){
delimStack.pop();
}else{
throw new IllegalStateException("Imbalanced delimiter detected.");
}
如果我正確地假設您的代碼在這里拋出異常,因為它期望一個DELIM_CLOSE類型的令牌但接收到DELIM_OPEN(假設您的輸入是'()')。
您應該檢查的是delimStack.pop()= token.type.DELIM_OPEN。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.