Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /////////////////////////////////////////////////////////////////////////////////////////// Class with static method
- public class LinkedListStaticMethods {
- public static boolean isBalanced(Queue<Character> q) throws Exception{
- boolean res=true, ex=false;
- Stack<Character> tmpSt=new LinkedListStack();
- int quSize=q.getSize();
- for (int i=0; i<quSize; i++){
- char tmpC=q.dequeue();
- q.enqueue(tmpC);
- if (tmpC=='(' || tmpC=='[' || tmpC=='{'){
- tmpSt.push(tmpC);
- } else if (tmpC==')' || tmpC==']' || tmpC=='}'){
- if (tmpC==')'){
- tmpC='(';
- } else if (tmpC==']'){
- tmpC='[';
- } else if (tmpC=='}'){
- tmpC='{';
- }
- if (tmpSt.getSize()==0 || tmpSt.pop()!=tmpC){
- res=false;
- }
- } else {
- ex=true;
- }
- }
- if (ex){
- throw new Exception("Illegel character was found.");
- }
- return res;
- }
- }
- /////////////////////////////////////////////////////////////////////////////////////////// Test Class
- public class testClass {
- public static void main(String[] args){
- Queue<Character> myQ=new LinkedListQueue();
- String s="({[][]})()";
- for (int i=0; i<s.length(); i++){
- myQ.enqueue(s.charAt(i));
- }
- System.out.println(myQ);
- try {
- System.out.println("is balances: "+LinkedListStaticMethods.isBalanced(myQ));
- } catch (Exception ex){
- System.out.println(ex.getMessage());
- }
- System.out.println(myQ+"\n");
- s="({[])})";
- myQ.clear();
- for (int i=0; i<s.length(); i++){
- myQ.enqueue(s.charAt(i));
- }
- System.out.println(myQ);
- try {
- System.out.println("is balances: "+LinkedListStaticMethods.isBalanced(myQ));
- } catch (Exception ex){
- System.out.println(ex.getMessage());
- }
- System.out.println(myQ+"\n");
- s="()))";
- myQ.clear();
- for (int i=0; i<s.length(); i++){
- myQ.enqueue(s.charAt(i));
- }
- System.out.println(myQ);
- try {
- System.out.println("is balances: "+LinkedListStaticMethods.isBalanced(myQ));
- } catch (Exception ex){
- System.out.println(ex.getMessage());
- }
- System.out.println(myQ+"\n");
- s="({[]ff)})";
- myQ.clear();
- for (int i=0; i<s.length(); i++){
- myQ.enqueue(s.charAt(i));
- }
- System.out.println(myQ);
- try {
- System.out.println("is balances: "+LinkedListStaticMethods.isBalanced(myQ));
- } catch (Exception ex){
- System.out.println(ex.getMessage());
- }
- System.out.println(myQ+"\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment