栈的应用:检查每件事情是否能成对出现,算法叙述:
做一个空栈。读入字符直到文件结尾。如果字符是一个开放符号,则将其推入栈中。如果字符是一个封闭符号,则当栈为空时报错。否则,将栈元素弹出。如果弹出的符号不是对应的开放符号,则报错。在文件结尾,如果栈非空则报错。
public class BalanceSigned { @SuppressWarnings("unchecked") public static void checkChar(char[] words,int size){ boolean error = false; //创建空栈 Stack s = createStack(); for(char c:words){ switch(c){ case ‘(‘: case ‘{‘: case ‘[‘: s.push(c); break; case ‘)‘: case ‘}‘: case ‘]‘: if(s.isEmpty()){ System.out.println("Error,"+ c +" is no match."); }else{ char cc = (char) s.pop(); if((c==‘)‘&&cc!=‘(‘)||(c==‘}‘&&cc!=‘{‘)||(c==‘]‘&&cc!=‘[‘)){ System.out.println("Error,"+ cc +" mismatch "+ c); } } break; } } if(!s.isEmpty()){ System.out.println("Error,sign is remaining."); } } public static Stack createStack(){ Stack s = new Stack(); return s; } public static void main(String[] args) { char[] ch ={‘(‘,‘2‘,‘}‘,‘}‘}; checkChar(ch,3); } }
时间: 2024-10-07 16:45:32