Stack2540Array
import java .io .*;
import java . util .*;
public class Stack2540Array {
int CAPACITY = 128;
int top ;
String [] stack ;
public Stack2540Array () {
stack = new String [ CAPACITY ];
top = -1;
}
1
3.1 Implement the stack ADT using array 3 TASKS
public int size () { return top + 1; }
public boolean isEmpty () { return (top == -1); }
public String top () {
if ( top == -1)
return null ;
return stack [ top ];
}
public void push ( String element ) {
top ++;
stack [top ] = element ;
}
3.1.2 Test Your Stack with the Parentheses Matching Problem You will test your Stack2540Array on an application, i.e., parentheses matching. It takes a string that contains parentheses that are often found in arithmetic expressions, and checks whether the brackets are correct (balanced) or incorrect (unbalanced). Example of valid strings are:
final static String [] valid = { "( ) ( ( ) ) {( [ ( ) ] ) } ",
" (3) (3 + (4 - 5) ) {( [ ( ) ] ) } ",
" ((() (() ) {([() ]) }))",
" [(5+ x) -(y+z)]" };
Examples of invalid strings are:
final static String [] invalid ={ ") (() ) {([() ])}",
" ({[]) }",
"(" };
You will write a method named isMatched like below. It will return true for valid strings, and false for invalid strings. You will use the stack named Stack2540Array that is implemented in the rst step. The algorithm itself can be the same as in our lecture slides. Your program does not need to check the correctness of the arithmetic operators/operands. What you need to do is to check for balanced brackets.
public static boolean isMatched ( String expression ) {
final String opening = " ({[ ";
final String closing = ")}]";
Stack2540Array buffer = new Stack2540Array ();
... ... return ...;
}
Please make the answer on java.
IMPLEMENTED pop() OPERATION IN ABOVE STACK
public String pop()
{
// if the stack is empty
if(top==-1)
return null;
String ans = stack[top];
top--;
return ans;
}
WHOLE PROGRAM WITH pop() FUNCTION :
import java . io .*;
import java . util .*;
class Stack2540Array {
int CAPACITY = 128;
int top;
String[] stack;
public Stack2540Array() {
stack = new String[CAPACITY];
top = -1;
}
public int size() {
return top + 1;
}
public boolean isEmpty() {
return (top == -1);
}
public String top() {
if (top == -1)
return null;
return stack[top];
}
public void push(String element) {
top++;
stack[top] = element;
}
public String pop()
{
//if the stack is empty
if(top==-1)
return null;
String ans = stack[top];
top--;
return ans;
}
}
Get Answers For Free
Most questions answered within 1 hours.