class StackObject { char cr; int loc; public StackObject(char c, int l) { cr = c; loc = l; } } class ListEl { Object obj; ListEl next; public ListEl(Object o) { obj = o; next = null; } } class MyStack { ListEl start; public MyStack() { start = null; } public void push (Object o) { ListEl newEl = new ListEl(o); newEl.next = start; start = newEl; } public Object pop () { if (start == null) {return null;} else { ListEl temp = start; start = temp.next; temp.next = null; return temp.obj; } } } class Auxiliaries { public static boolean matches(char a, char b) { boolean ans = false; if (( a == '(') && (b == ')' )) ans = true; if ((a == '[' ) && (b == ']' )) ans = true; return ans; } } public class ParanthList { public static void main (String argv []) { char [] str = {'(', '[', ']', '[', ']',']'}; //string to be processed StackObject ObjectOnTop; int i = 0; // to iterate through str boolean done = false; //variable to indicate mismatch in the middle of processing str MyStack sta = new MyStack(); while( (i < str.length) && ! done) { if ( (str[i] == '(') || (str[i] == '[')) { sta.push(new StackObject(str[i],i)); } // push onto stack for open paranths else if( (str[i] == ')') || (str[i] == ']') ) { ObjectOnTop = (StackObject) sta.pop(); // pop otherwise, and process as below if (ObjectOnTop == null) { done = true; System.out.println("The character " + str[i] + " at position" + i + "has no match"); } else if (! Auxiliaries.matches(ObjectOnTop.cr, str[i]) ) { done = true; System.out.println("The " + str[i] + " at position " + i + " does not match the " + ObjectOnTop.cr + " at position " + ObjectOnTop.loc); } } else {System.out.println("invalid character at position" + i); done = true; } // Only used if str contains something other than paranths i++; } if ( !done && (sta.pop() != null) ) System.out.println("Paranths need to be closed"); } }