2 Introduction To Data Structures and Stack
2 Introduction To Data Structures and Stack
Data Structures
. . . …………
Frame
of D( )
A( ) B( ) C()
{ { { Frame
B( ) ; C( ); D( ) ; of C( )
: : : Frame
: : : of B( )
} } } Frame
of A( )
5
1 top
12
Introduction to Data Structures
Stack Implementation
public class StackArray {
private int top; // will point to the topmost element of the stack
private Object[] storage;
public StackArray(int n){
int size = n;
storage = new Object[size];
top = -1;
}
Conditions:
• Every open bracket should be closed by the appropriate
close bracket.
• No extra close brackets.
• The last bracket opened should be closed first.
Introduction to Data Structures
Pseudo Code
valid = true // assume string is valid so far
Stack s = new Stack(); s.clear();
while (valid & (input not over )){
read next symbol (symb) ;
if (symb is ‘(‘ or ‘[‘ or ‘{‘ ){
s.push(symb);
}
else if (symb is ‘)’ or ‘]’ or ‘}’ ){
if (s.isEmpty()) valid = false // too many closing brackets
i = s.pop()
if (i does not match with symb) valid = false
}
}