EC-211 DATA STRUCTURES
LECTURE 5
2
Stack Data Structure
Stack of Books Stack of Notes Stack of Gifts
THE STACK
• A stack is an ordered collection of items in which insertions and deletions are done only at one end, called the Top of the stack.
E
D
C
B
A
top
AB
A
C
B
A
D
C
B
A
C
B
A
E
C
B
A
(a) (b) (c) (d) (e) (f)
Motion Picture of a Stack
Notice the Last-in-First-out (LIFO) Behavior
Operations
• Push– Insertion of an item at top of stack
• Pop– Removal of an item from top of stack– Not defined for empty stack (underflow)
Other Operations on Stack
• Checking whether the stack is empty– returns TRUE if the stack is empty– returns FALSE if there is at least one item in the
stack
Stack Applications
• Nested Parentheses– In mathematical expressions that include sets of
nested parenthesis; we want to ensure that1.There are an equal number of right and left
parentheses• ((A+B)
2.Every right parenthesis is preceded by a matching left parenthesis• (A+B))-(C+D
Checking for Balanced Parentheses with StacksLet S be an empty stackBalanced SoFar = TRUEI=0while(I < strlen (Str) and BalancedSoFar ){ Ch = Str [ I ]
++I//push an open braceif ( Ch is ‘(‘ )
Push ‘(‘ on S//Close Braceelse if ( Ch is ‘)’ )
if ( S is not empty)Pop top item from S//pop a matching open
braceelse //no matching open brace
BalancedSoFar = FALSE
Checking for Balanced Parentheses with Stacks
//ignore all characters other than braces
} //end while
if ( BalancedSoFar and S is Empty )Str has Balanced Braces
elseStr does not have balanced Braces
Checking Multiple Types of Brackets
{
(
{
[
(
{
(
{ {
(
{
[
(
Example:{x+(y-[a+b])*c-(d+e)}/(h-[j-k])
{ {x+( {x+(y-[ {x+(y-[a+b] {x+(y-[a+b]) {x+(y-[a+b])*c-(
{x+(y-[a+b])*c-(d+e)} {x+(y-[a+b])*c-(d+e)}/(h-[j-k {x+(y-[a+b])*c-(d+e)}/(h-[j-k])
Checking Multiple Types of Brackets
valid=true; s=the empty stack; while (we have not read the entire string) {
read the next symbol (symb) of the string; if (symb==‘(‘ || symb==‘[‘ || symb==‘{‘)
push(s, symb);
Multiple Types of Brackets contd.
if (symb==‘)‘ || symb==‘]‘ || symb==‘}‘) if (empty(s))
valid=false; else {
i=pop(s);if (i is not the matching opener of symb);
valid=false;} //end else
} //end while
Multiple Types of Brackets contd.
if (!empty(s))valid=false;
if (valid)
cout<<“the string is valid”; else
cout<<“the string is invalid”;
Top Related