Skip to content

Instantly share code, notes, and snippets.

@panwarab
Created September 15, 2018 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panwarab/3fa68dcbe6f925d7e959d26df2f1536f to your computer and use it in GitHub Desktop.
Save panwarab/3fa68dcbe6f925d7e959d26df2f1536f to your computer and use it in GitHub Desktop.
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