Created
September 15, 2018 04:45
-
-
Save panwarab/3fa68dcbe6f925d7e959d26df2f1536f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package strings; | |
import java.util.Scanner; | |
class StackNode { | |
private String expression; | |
private StackNode below; | |
public StackNode getBelow() { | |
return below; | |
} | |
public void setBelow(StackNode below) { | |
this.below = below; | |
} | |
public String getExpression() { | |
return expression; | |
} | |
public void setExpression(String expression) { | |
this.expression = expression; | |
} | |
} | |
class Stack { | |
private StackNode top; | |
public void push(String element) { | |
StackNode node = new StackNode(); | |
node.setExpression(element); | |
node.setBelow(top); | |
top = node; | |
} | |
public boolean isEmpty() { | |
return top == null; | |
} | |
public StackNode pop() { | |
StackNode result = top; | |
if (top != null) { | |
top = top.getBelow(); | |
} | |
return result; | |
} | |
public StackNode peek() { | |
return top; | |
} | |
/** | |
* To implement a 1-based indexing in the stack | |
* | |
* @return | |
*/ | |
public StackNode search() { | |
return null; | |
} | |
} | |
public class ParenthesisChecker { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
System.out.println("Input expression here\n"); | |
String input = sc.next(); | |
Stack myStack = new Stack(); | |
for (int i = 0; i < input.length(); i++) { | |
if (input.charAt(i) == '(') { | |
myStack.push("("); | |
} else { | |
myStack.pop(); | |
} | |
} | |
System.out.println((myStack.isEmpty()) ? "Expression is valid" : "It is not a valid expression"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment