-
Notifications
You must be signed in to change notification settings - Fork 45
/
exprBal.java
78 lines (68 loc) · 1.84 KB
/
exprBal.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.Scanner;
public class exprBal {
static node head;
static class node {
char data;
node next;
node(char d) {
this.data = d;
}
}
public static void push(char dt) {
node newNode = new node(dt);
if (head == null) {
head = newNode;
return;
}
newNode.next = head;
head = newNode;
}
public static char pop() {
char x = head.data;
head = head.next;
return x;
}
static boolean exprbal(String expr) {
for (int i = 0; i < expr.length(); i++) {
char x = expr.charAt(i);
if (x == '(' || x == '[' || x == '{') {
push(x);
}
if (head == null) {
return false;
}
char check;
switch (x) {
case ')':
check = pop();
if (check == '{' || check == '[')
return false;
break;
case '}':
check = pop();
if (check == '(' || check == '[')
return false;
break;
case ']':
check = pop();
if (check == '(' || check == '{')
return false;
break;
}
}
boolean x = false;
if (head == null) {
x = true;
}
return x;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("enter expression to evaluate:");
String expr = in.nextLine();
if (exprbal(expr))
System.out.println("Balanced ");
else
System.out.println("Not Balanced ");
}
}