Parenthesis matching using Stack.
import java.util.*;
class Node {
protected int data;
protected Node next = null;
public Node() {
}
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
void setData(int data) {
this.data = data;
}
void setLink(Node link) {
this.next = link;
}
Node getLink() {
return next;
}
int getData() {
return data;
}
}
class Stack {
protected Node top = null;
public void push(int val) {
// Currently we have set no limits to pushing elements
Node nptr = new Node(val, top);
top = nptr;
}
public int pop() throws Exception {
if (isEmpty()) {
throw new Exception("Stack Underflow");
} else {
int val = top.getData();
top = top.getLink();
return val;
}
}
public boolean isEmpty() {
return top == null;
}
public void show() {
Node ptr = top;
while (ptr != null) {
System.out.printf("%d, ", ptr.getData());
ptr = ptr.getLink();
}
}
}
public class MatchParenStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.printf("Enter string to Match Parenthesis:\n");
String val = sc.nextLine();
Stack stk = new Stack();
for (int x = 0; x < val.length(); x++) {
char ch = val.charAt(x);
if (ch == '(')
stk.push(x);
else if (ch == ')')
try {
int ind = stk.pop();
System.out.printf("The ) at index %d matched with ( at index %d\n", x, ind);
} catch (Exception e) {
System.out.printf("The ) at index %d is UNMATCHED!!\n", x);
}
}
while (!stk.isEmpty()) {
try {
System.out.printf("The ( at index %d is UNMATCHED!!\n", stk.pop());
} catch (Exception e) {
}
}
sc.close();
}
}
Name | Type | Uses |
---|---|---|
Class Node | ||
global | ||
data | int | value to be stored in the current node |
link | Node | pointer for the next node |
Class Stack | ||
global | ||
top | Node | topmost element in the stack |
public void push(int val) | ||
nptr | Node | to store the new pointer which will eventually become the top |
public int pop() | ||
val | int | to temporarily store data of the top most element to be returned |
public void show() | ||
ptr | Node | a pointer to be used in the loop to traverse in the stack |
Class MatchParenStack | ||
void main() | ||
sc | Scanner | object to accept user input |
val | String | to store entered expression to evaluate |
stk | Stack | a stack data type object to help us in parenthesis matching |
x | int | counter variable to iterate over 'val' |
ch | char | to store current extracted character |