Download presentation
Presentation is loading. Please wait.
Published bySolomon Hopkins Modified over 9 years ago
1
EC-211 DATA STRUCTURES LECTURE 5
2
2 Stack Data Structure Stack of Books Stack of Notes Stack of Gifts
3
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
4
A B 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
5
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)
6
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
7
Stack Applications Nested Parentheses – In mathematical expressions that include sets of nested parenthesis; we want to ensure that 1.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
8
Checking for Balanced Parentheses with Stacks Let S be an empty stack Balanced SoFar = TRUE I=0 while(I < strlen (Str) and BalancedSoFar ) {Ch = Str [ I ] ++I //push an open brace if ( Ch is ‘(‘ ) Push ‘(‘ on S //Close Brace else if ( Ch is ‘)’ ) if ( S is not empty) Pop top item from S//pop a matching open brace else //no matching open brace BalancedSoFar = FALSE
9
Checking for Balanced Parentheses with Stacks //ignore all characters other than braces }//end while if ( BalancedSoFar and S is Empty ) Str has Balanced Braces else Str does not have balanced Braces
10
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])
11
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);
12
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
13
Multiple Types of Brackets contd. if (!empty(s)) valid=false; if (valid) cout<<“the string is valid”; else cout<<“the string is invalid”;
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.