数据结构2_java---栈,括号匹配
1 package Main; 2 3 4 import java.util.Scanner; 5 6 import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction; 7 8 /*栈操作*/ 9 public class Main{ 10 public int maxsize; 11 public int top; 12 private Object[] stackelem; 13 //初始化 14 public Main(int maxstack) 15 { 16 top = 0; 17 this.maxsize = maxstack; 18 stackelem = new Object[maxstack]; 19 } 20 //将栈置空 21 public void clear() 22 { 23 top = 0; 24 } 25 //判断栈是否为空 26 public boolean isEmpty() 27 { 28 if(top==0) 29 return true; 30 return false; 31 } 32 //入栈 33 public void push(Object x) throws Exception 34 { 35 if(top==maxsize) 36 throw new Exception("the stack is enough"); 37 stackelem[top] = x; 38 top++; 39 } 40 //从顶端开始输出所有栈内内容 41 public void print() { 42 for(int i=top-1;i>=0;i--) 43 { 44 System.out.println(stackelem[i]); 45 } 46 } 47 //出栈 48 public Object pop() throws Exception 49 { 50 if(isEmpty()) 51 throw new Exception("the stack is empty!"); 52 top--; 53 return stackelem[top]; 54 } 55 public static void main(String[] args) throws Exception { 56 Main aStack = new Main(100); 57 Scanner aScanner = new Scanner(System.in); 58 String aString = aScanner.nextLine(); 59 char []a = new char[aString.length()]; 60 a = aString.toCharArray(); 61 Main bStack = new Main(100); 62 for(int i=0;i<a.length;i++) 63 { 64 aStack.push(a[i]); 65 } 66 int flag=1; 67 char pop; 68 for(int i=0;i<a.length;i++) 69 { 70 pop = (char) aStack.pop(); 71 if(pop==')') 72 { 73 bStack.push(pop); 74 }else if(pop=='('&&bStack.isEmpty()){ 75 flag = 0; 76 77 }else if(pop=='(') 78 { 79 bStack.pop(); 80 } 81 } 82 if (bStack.isEmpty()&&flag==1) { 83 System.out.println("The String is right!"); 84 }else { 85 System.out.println("the string is wrong!"); 86 } 87 aStack.print(); 88 89 90 } 91 }
使用java实现栈的操作,同时加入了括号匹配实现应用;
括号匹配:
(1)将所有输入的字符串压入栈中
(2)依次取出,遇到‘)’,则将其压入新栈中。
(3)遇到‘(’,则从新栈中取出与之匹配,判断最后栈是否为空;
(4)需要注意的是,第一个括号为反的情况,设置标志位flag用于判断。