You are on page 1of 28

More on Stacks and Queues and Backtracking

A.R. Hadaegh Dr. Ahmad R. Hadaegh California State University San Marcos (CSUSM) Page 1

• As we mentioned before, two common introductory Abstract Data Type (ADT) that worth studying are Stack and Queue • Many problems (or parts of problems) can be thought of as stack problems, queue problems, or other problems that can be solved with the help of another (perhaps user-defined) ADT

• You need to decide what ADTs you need, build them, test them, then tackle your larger problem

A.R. Hadaegh Dr. Ahmad R. Hadaegh

California State University San Marcos (CSUSM)

Page

2

etc A. Hadaegh Dr.Stack ADT • A stack is an ADT with specific properties and operations • Stack properties are: • Only one item can be accessed at a time • Always the last item inserted is the first to come out (LIFO) • New items must be inserted at the top • The size of the stack is dynamic • The stack must be able to grow and shrink • Normally. they are all integers or all are string. items stored on the stack are homogeneous (i.R. e. Ahmad R. Hadaegh California State University San Marcos (CSUSM) Page 3 .

Can’t push into a full stack • Pop: Removes the top item from stack. Hadaegh California State University San Marcos (CSUSM) Page 4 . Hadaegh Dr. Can’t top an empty stack • Init: Set existing stack to empty • Full: Returns true if the stack is full • Empty: Returns true if the stack is empty A.Stack Operations • Stack operations are: • Push: Puts a new item on the top of the stack. Ahmad R.R. Can’t pop an empty stack • Top: Examine top item without modifying stack.

Hadaegh Dr.Problem Solving Using Stack: Bracket Checking • Many problems can be solved using stacks • Given a mathematical expression with 3 types of “brackets” ( ) [ ] { }. Ahmad R. Hadaegh California State University San Marcos (CSUSM) Page 5 . bracketing in the following expression is CORRECT { 5 * (8-2) } / { [4 * (3+2)] + [5 * 6] } • However.R. we want to determine if the brackets are properly matched • For example. the bracketing in the following two expressions are INCORRECT { (A+C) * D [A + {B+C} ) A.

Hadaegh California State University San Marcos (CSUSM) Page 6 . Ahmad R. report illegal bracketing A. pop the stack • If not. push it onto the stack • When a right bracket is encountered. report illegal bracketing • If there are items left on the stack after the expression has been scanned.R. compare it to the top item on the stack • If it’s a match.• This problem is easily solved with a stack • Algorithm: • Scan expression from left to right • Each time a left bracket is encountered. report illegal bracketing • If the stack is prematurely empty. Hadaegh Dr.

This program assumes bool BracketMaching (string expression) that we have the { following routines char curr. char top (). i++) bool empty (). Ahmad R.size(). i< stg. else if (bracket_stack. temp. Hadaegh California State University San Marcos (CSUSM) Page 7 . Hadaegh Dr. } A.R.push (curr). end if end if } // for loop return true.pop() does not match with curr) return false. available Stack bracket_stack. { push (item).empty() ) then return false. curr = stg[i]. if (curr == „(‟ || curr == „[‟ || curr == „{‟) bracket_stack. for (int i=0. else if (curr == „)‟ || curr == „]‟ || curr == „}‟) if (bracket_stack.

when we write an arithmetic expression as follows: 2 + 3 * (6 .Problem Solving Using Stack: Evaluation of An Expression • Consider the problem of evaluating an arithmetic expression using a stack • Traditionally. Hadaegh California State University San Marcos (CSUSM) Page 8 .5) • This is known as infix notation • Operators are in-between the operands • When computing arithmetic expressions. Hadaegh Dr.R. Ahmad R. it’s sometimes useful to represent them using postfix (operator after) or prefix (operator before) notation A.

Prefix -61 *+432 /+23-94 Infix 6-1 (4 + 3) * 2 (2 + 3) / (9 . Hadaegh Dr.R.4) Postfix 6143+2* 23+94-/ • It’s easy to evaluate postfix and prefix expressions using a stack in part because no brackets are necessary A. Ahmad R. Hadaegh California State University San Marcos (CSUSM) Page 9 .

R. Hadaegh Dr. Hadaegh postfix 43+2* 3 2 * 14 4 + 7 push 4 push 3 Pop 3 Pop 4 Apply addition and get 7 Push 7 Push 2 Pop 2 Pop 7 Apply * and get 14 Push 14 Page 10 California State University San Marcos (CSUSM) .prefix *+432 evaluate 4 7 + 3 2 * 14 2 Push 2 Push 3 Push 4 Pop 4 Pop 3 Apply + and get 7 Push 7 Pop 7 Pop 2 Apply * and get 14 Push 14 A. Ahmad R.

R. pop the top two operands. and push the result onto the stack • When the expression is completely scanned. push it onto the stack • When an operator is encountered.6) / 2] becomes 2356-2/*+ A. the final result will be on the stack • What if we want to convert an expression from infix to postfix? • For example: 2 + 3 * [(5 . apply the operator. Hadaegh Dr. Ahmad R.• Algorithm for evaluating postfix: • Parse expression from left to right • When an operand is encountered. Hadaegh California State University San Marcos (CSUSM) Page 11 .

• If the priority is >= the current operator.R. copy it to the output • When a bracket is encountered. pop the top operator and copy it to output • Continue until an operator of lesser priority is encountered or until stack is empty • Assume left brackets have lowest priority • Finally. Discard the left bracket. • When an operator is encountered. Ahmad R. Hadaegh Dr. Hadaegh California State University San Marcos (CSUSM) Page 12 . check the top item of the stack. pop all operators out of the stack and copy them to output until a matching left bracket is encountered. push current operator onto the stack • When the end of the expression is reached.• Use the following algorithm to change infix to postfix: • Scan infix string from left to right • Each time an operand is encountered. • Push left brackets onto the stack • If it’s a right bracket. copy the remaining stack contents to output in the order popped A. check its orientation.

Hadaegh California State University San Marcos (CSUSM) . Note there is no operator on the top of the stack with priority >= the + operator Page 13 A.R. Ahmad R. Hadaegh Dr.• Consider the following example that is scanned from left to right Expression: 2+3*[(5–6)/2] Stack Output: 2 • 2 is placed on the output line because it is an operand Expression: 2+3*[(5–6)/2] Stack Output: 2 + • + is an operator and it is placed in the stack.

Expression: 2+3*[(5–6)/2] Stack Output: 23 + • 3 is placed on the output line because it is an operand Expression: 2+3*[(5–6)/2] Stack Output: 23 * + A. Hadaegh • * is an operator and it is placed in the stack without taking anything out of the stack. Hadaegh Dr.R. Note that * has higher priority than + Page 14 California State University San Marcos (CSUSM) . Ahmad R.

R.Expression: 2+3*[(5–6)/2] Stack Output: 23 [ * + • Left brackets. Hadaegh Dr. Ahmad R. Hadaegh California State University San Marcos (CSUSM) Page 15 . it is placed in the stack Expression: 2+3*[(5–6)/2] Stack ( [ * + Output: 23 • Again another left encountered and it is placed in the stack A. no matter what type of bracket it is.

Note that the top of the * stack is not an operator to + compare minus sign with it Page 16 A.Expression: 2+3*[(5–6)/2] Stack Output: 235 ( [ * + • 5 is placed on the output line because it is an operand Expression: 2+3*[(5–6)/2] Stack Output: 235 ( • Minus sign (-) is placed in the [ stack. Ahmad R.R. Hadaegh Dr. Hadaegh California State University San Marcos (CSUSM) .

Hadaegh • “(” is a closing round bracket. Keep on popping from the stack till we you find the matching opening round bracket.R. Ahmad R. Hadaegh Dr.Expression: 2+3*[(5–6)/2] Stack Output: 2356 ( [ • 6 is placed on the output line * because it is an operand + Expression: 2+3*[(5–6)/2] Stack Output: 2356- [ * + A. DO NOT COPY THE OPEN ROUND BRACKET TO THE OUTPUT Page 17 California State University San Marcos (CSUSM) .

Hadaegh Dr.Expression: 2+3*[(5–6)/2] Stack / [ * + Output: 2356- • Division (/) is placed in the stack. Note that the top of the stack is not an operator to compare division sign with it Expression: 2+3*[(5–6)/2] Stack / [ * + Output: 2356-2 • 2 is placed on the output line because it is an operand A.R. Hadaegh California State University San Marcos (CSUSM) Page 18 . Ahmad R.

DO NOT COPY THE OPEN SQUARE BRACKET TO THE OUTPUT Expression: 2+3*[(5–6)/2] Output: 2356–2/*+ • We are done.Expression: 2+3*[(5–6)/2] Stack Output: 2356-2/ * + Stack • “]” is a closing square bracket. Ahmad R. Hadaegh Dr. Hadaegh California State University San Marcos (CSUSM) Page 19 .R. Keep on popping from the stack till we you find the matching opening square bracket. So keep popping from the stack and place the characters to the output line • What we have on the output line is the corresponding postfix expression A.

Problem Solving Using Stack: Adding large numbers using stack • Another example of stack application is adding two large numbers together.R. Hadaegh California State University San Marcos (CSUSM) Page 20 . Hadaegh Dr. • Note that the largest magnitude of integers are limited so we are not able to normally add numbers like: 243678489505654679857465758598595950949463535 + 462668435748955758056548577946 • Since the integer variables cannot hold such a big numbers we can use other tools to add these numbers together • The next slide shows the algorithm of adding two numbers together using stack A. Ahmad R.

R. Hadaegh California State University San Marcos (CSUSM) Page 21 . • While at least one stack is not empty • Pop a number from each stack and add them to R.Algorithm for adding two numbers • Read the numerals of the first number and store the numbers corresponding to them on the stack. • Read the numerals of the second number and store them in another stack. • Let R = 0. Ahmad R. • Store carry part of R in R overwriting the old value. • Push R on the result stack if it is not zero • Pop numbers from the result stack and display them A. • Push the unit part of R on the result stack. Hadaegh Dr.

R. Hadaegh 6 7 6 3 7 6 4 3 7 6 Page 22 California State University San Marcos (CSUSM) . Ahmad R.592 + 3784 4376 2 +4 6 9 +8 17 1 5 +7 13 1 +3 4 2 Stack 1 9 5 9 5 5 + =6 4 Stack 2 8 7 3 8 7 3 + =17 7 3 + =13 + =4 3 Result Stack A. Hadaegh Dr.

• When a cell is visited. Ahmad R. • The maze is implemented as a two dimensional character array in which passages are marked with “o” and walls are marked with “1”.” so that the mouse does not try that again. • As long as it finds a space it moves in that path and tries its best to find the exit door. • In general. it is marked with “. • We represent the mouse with M and exit door with E A. Hadaegh California State University San Marcos (CSUSM) Page 23 .Problem Solving Using Stack: Exiting A Maze • Consider the problem of a trapped mouse that tries to find its way to an exit in a maze • The mouse systematically moves and if it hits a wall. if it cannot succeed. the mouse always takes right cell first. it takes left and if it still fails. it backtracks and tries another path. Hadaegh Dr. it takes down and finally it tries the upper cell to reach its destination.R.

entryCell. • Thus the mouse will be trapped in the maze until it finds the door. we create a wall around the maze.• In order to ensure that the mouse does not fall off the maze. down left and right If stack is empty Report failure Else Pop off a cell from the stack and make it currentCell success A. currentCell = entryCell. Hadaegh Dr. exitCell. otherwise. Hadaegh California State University San Marcos (CSUSM) Page 24 . we report a failure. Push onto the stack the unvisited neighbors of current Cell in the order of up. • The algorithm is: Initialize stack. Create a wall of 1‟s around the maze While currentCell is not exitCell Mark currentCell as visited. Ahmad R.R. • If the mouse tries all the possible solutions and still cannot find the exit door. we report a success.

Ahmad R. Hadaegh Dr. 3) A.R.0 1 2 3 4 5 Start with the following maze where the mouse is at position (3. Hadaegh California State University San Marcos (CSUSM) Page 25 . 3) and the exit door is at (2. 4) 0 1 2 3 4 1 1 1 1 1 1 1 1 1 o o 1 1 o o o E 1 1 o o M 1 1 1 1 1 1 1 1 0 1 2 3 4 5 0 1 2 3 4 1 1 1 1 1 1 1 1 1 o o 1 1 o o o E 1 1 o o M 1 1 1 1 1 1 1 1 Push the Up and Left cell into stack Make the current position visited (“.”) Pop the first element of the stack Move the mouse to that position (3. 2) (2.

3) 0 1 2 3 4 5 Push the Up cell into stack Make the current position visited (“.”) Pop the first element of the stack Move the mouse to that position 1 o o o E 1 1 o M . Hadaegh California State University San Marcos (CSUSM) Page 26 . 1) (2.0 1 2 3 4 5 0 1 2 3 4 1 1 1 1 1 1 1 1 1 o o 1 Push the Up and Left cells into stack Make the current position visited (“. 2) (2. 3) A. .”) Pop the first element of the stack Move the mouse to that position 0 1 2 3 4 1 1 1 1 1 1 1 1 1 o o 1 1 o o o E 1 1 M . 1) (2. 2) (2. Ahmad R.R. 1 1 1 1 1 1 1 1 (2. Hadaegh Dr. 1 1 1 1 1 1 1 1 (3.

”) Pop the first element of the stack Move the mouse to that position (2. 2) (2. Ahmad R. 3) (2. 2) (2. Hadaegh Dr. Hadaegh California State University San Marcos (CSUSM) Page 27 . 2) (2. 1 1 1 1 1 1 1 1 (2. . . 3) 1 1 1 1 1 1 A.R. 1 . M o E 1 .0 1 2 3 4 5 0 1 2 3 4 1 1 1 1 1 1 1 1 1 o o 1 Push the Right cell into stack Make the current position visited (“. . 1 1 Push the Right cell into stack Make the current position visited (“. 3) 0 1 2 3 4 5 0 1 2 3 4 1 1 1 1 1 1 1 1 1 o o 1 1 .”) Pop the first element of the stack Move the mouse to that position 1 M o o E 1 1 .

Hadaegh California State University San Marcos (CSUSM) Page 28 . 1 o 1 1 1 1 1 1 Push the UP cell into stack E/M 1 1 1 1 1 (1. 3) The exit door is found A. 2) (2. . 2) (2. 1 1 1 1 1 1 1 1 (2.R. 3) (2. .”) Pop the first element of the stack Move the mouse to that position 1 . Ahmad R. . 3) 0 1 2 3 4 5 0 1 2 3 4 1 1 1 1 1 1 1 o 1 . . M E 1 . Hadaegh Dr. 1 . 1 . . 3) (2.0 1 2 3 4 5 0 1 2 3 4 1 1 1 1 1 1 1 1 1 o o 1 Push the UP and Right cell into stack Make the current position visited (“. 4) (1. .