java - Working with Linked List Stacks -


public class matcher {  public matchrtncode matcher(string str){      stack<character> s=new llstack<character>();     for(int =0; i<str.length(); i++){         char c=str.charat(i);         if(c=='{' || c=='[' || c=='('){             s.push(c);         }else if (c=='}'){             character temp=s.pop();             if(temp!='{'){                 s.push(temp);                 return matchrtncode.unexpected_symbol;             }           }else if (c==']'){             character temp=s.pop();             if(temp!='['){                 s.push(temp);                 return matchrtncode.unexpected_symbol;             }          }else if (c==')'){             character temp=s.pop();             if(temp!='('){                 s.push(temp);                 return matchrtncode.unexpected_symbol;             }          }else{          }     }     character temp = s.pop();     if(temp=='{' || temp=='[' || temp=='('){         return matchrtncode.too_many_open_symbols;     }else if(temp=='}' || temp==']' || temp==')'){         return matchrtncode.too_many_closed_symbols;     }else {         return matchrtncode.good_string;     }  } } 

the stack class is:

 import java.util.emptystackexception;   public interface stack<e> {  public void push(e data) throws stackfullexception; public e pop() throws emptystackexception; public boolean isempty() throws emptystackexception; 

}

and llstack class is:

 import java.util.emptystackexception;   public class llstack<e> implements stack<e> { public node top; private class node{     public e data;     public node next;     public node(e data, node next){         this.data=data;         this.next=next;     } }  public llstack() {     top = null; }  @override public void push(e data) throws stackfullexception {      top=new node(data, top); }  @override public e pop() throws emptystackexception {     if(top==null){         throw new emptystackexception();     }     e data=top.data;     top=top.next;     return data; }  @override public boolean isempty() {     return top==null; } } 

i checking string example: {[(ab)]} make sure there same number of {[( there }]). right printing out emptystackerror. how fix this?

 if(s.pop()=='{'){      s.pop();  } 

pop() changes state of stack. either need peek or remember push on once pop() , don't need it.

so try:

 char temp = s.pop();  if(temp != '{') {      s.push(temp);  } 

or make peek method:

public char peek() {     char c = s.pop();     s.push(c);     return c; } 

use instead of construct if (s.pop() == '}')


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -