class StackObject { String str; int loc; public StackObject(String s, int l) { str = s; 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(String a, String 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 []) { String [] str = {"[","(", "[", "]", ")", "[", ")"}; //string to be processed StackObject ObjectOnTop; int i = 0; // to iterate through str boolean notDone = true; //variable to indicate mismatch in the middle of processing str MyStack sta = new MyStack(); while( (i < str.length) && notDone) { 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) { notDone = false; System.out.println("The character " + str[i] + " at position" + i + "has no match"); } else if (! Auxiliaries.matches(ObjectOnTop.str, str[i]) ) { notDone = false; System.out.println("The " + str[i] + " at position " + i + " does not match the " + ObjectOnTop.str + " at position " + ObjectOnTop.loc); } } else {System.out.println("invalid character at position" + i);} // Only used if str contains something other than paranths i++; } if ((sta.pop() != null) && notDone ) System.out.println("Paranths need to be closed"); } }