1 / 74

Dr. Jahangir UWP Data Structures Notes Unit-3

For students of University Women's Polytechnic

Download Presentation

Dr. Jahangir UWP Data Structures Notes Unit-3

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Unit – III Unit – III Stacks, Queues & Recursion

  2. Stack • A stack is a list of elements in which an element can be inserted or deleted only at one end. • The end is referred to as the “top of stack”. • So elements are removed from the stack in the reverse order of that in which they were inserted into the stack. 2­Nov­19 Jahangir Alam 2

  3. • This way a stack is a LIFO (Last in First Out) or FILO (First in Last Out) data structure Out) data structure. • Special terminology refer to the two basic operations associated with stack: PUSH PUSH: : is the term used to insert an PUSH: : is the term used to insert an element into the stack. ­ ­ POP POP: : is the term used to delete an element from the stack. is used to ­ ­ PUSH 2­Nov­19 Jahangir Alam 3

  4. An Example • Say pushed in order onto an empty pushed in order onto an empty stack: AAA, BBB, CCC, DDD, EEE, FFF • Following figures depict the above operations: operations: following six elements are 2­Nov­19 Jahangir Alam 4

  5. Empty Stack Empty Stack 15 14 13 12 11 11 10 9 8 7 6 5 4 3 2 1 15 14 13 12 11 11 10 9 8 7 6 5 5 4 3 2 1 15 14 13 12 11 11 10 9 8 7 6 5 5 4 3 2 1 TOP TOP BBB BBB AAA AAA TOP TOP AAA AAA TOP = NULL TOP = NULL

  6. 15 14 13 12 11 11 10 9 8 7 6 5 4 3 2 1 15 14 13 12 11 11 10 9 8 7 6 5 4 3 2 1 … … … … … …. TOP TOP FFF FFF EEE EEE DDD DDD CCC CCC BBB BBB AAA AAA CCC CCC BBB BBB AAA AAA TOP TOP

  7. Maintaining Stack in Memory • Can linked list. We shall discuss • We shall discuss array representation of stack. • Array representation requires following: ­ A linear array named as STACK ­ A pointer variable TOP TOP which contains the location of the top element of the stack. ­ A variable MAXSTK MAXSTK which gives the maximum number of elements that can be held by the stack. be maintained using arrays or representation of STACK. 2­Nov­19 Jahangir Alam 7

  8. • The condition TOP will indicate that the stack is empty. TOP = = 0 0 or TOP TOP = = NULL NULL Stack Stack 10 9 8 7 6 5 4 3 2 1 MAXSTK MAXSTK TOP = NULL TOP = NULL

  9. Operations on Stack • Operations: PUSH and POP • We have already looked into them • We have already looked into them. • So, its time to formally. discuss them 2­Nov­19 Jahangir Alam 9

  10. Algorithm for PUSH • Following (inserts) ITEM into STACK. (inserts) algorithm pushes PUSH (STACK, TOP, MAXSTK, ITEM) 1. [STACK already filled?] IF TOP = MAXSTK then: WRITE “Overflow” and RETURN 2. 2. SET TOP := TOP + 1 SET TOP := TOP + 1 3. SET STACK[TOP] := ITEM 4. END 2­Nov­19 Jahangir Alam 10

  11. Algorithm for POP • Following algorithm pops (deletes) ITEM from the STACK ITEM from the STACK. POP (STACK, TOP, MAXSTK, ITEM) 1. [STACK has an item to be removed?] IF TOP = NULL then: WRITE “Underflow” and RETURN 2. 3. SET ITEM := STACK[TOP] SET TOP := TOP - 1 4. END 2­Nov­19 Jahangir Alam 11

  12. Applications of Stacks • Stacks computer science computer science. • Their specific applications are: ­ Management of Function Calls ­ Evaluation of Expressions ­ Implementation of certain algorithms (e.g. Quick Sort). are widely used in ­ Implementation of certain algorithms 2­Nov­19 Jahangir Alam 12

  13. Evaluation of Expressions • Operators Precedence: ­ In arithmetic expressions operators expressions operators precedence is observed: Operator Exponential Multiplication & Division Addition & Subtraction Symbol Precedence Highest Next Highest Lowest ↑ * & / +/ ­ • An Example: ­ Evaluate 2↑3+5*2↑2­12/6 ­ Answer: 26 2­Nov­19 Jahangir Alam 13

  14. • An Important Fact: ­ Parentheses’ alter the precedence of operators. • An Example: ­ (A+B) *C ≠ A+(B*C) ­ (2+3) * 7 = 35 while 2+(3*7) = 23 • How computer arithmetic expressions? question we want to seek answer for. evaluates the the – is 2­Nov­19 Jahangir Alam 14

  15. Notations for Expressions • Infix Notations: ­ Expressions in which operator lies between the operands between the operands are referred to as infix notations. ­ A+B, C­D, P*F… notations. ­ A+(B*C) and A+(B*C) and distinguished by parentheses’ or by applying the operators discussed above. referred to all are infix (A+B) *C (A+B) *C are are precedence 2­Nov­19 Jahangir Alam 15

  16. • Prefix or Polish Notations ­ Named in mathematician, Jan Lukasiewiez, refer mathematician, Jan Lukasiewiez, refer to the expressions in which the operator symbol is placed operands. ­ +AB, ­CD, *PF… all are examples of prefix or polish expressions prefix or polish expressions. ­ Simple infix expressions converted to polish follows: honour of Polish before its two can be as expressions 2­Nov­19 Jahangir Alam 16

  17. ­ (A+B) *C = [+AB]*C = *+ABC ­ A+(B*C) = A+[*BC] = +A*BC ­ (A+B) /(C ­D) /+AB­CD • An important notations is parentheses' free parentheses' free. = [+AB]/[­CD] = property that of these are they 2­Nov­19 Jahangir Alam 17

  18. • Postfix or Reverse Polish Notations ­ Refer to the expressions in which Refer to the expressions in which operator is placed after its two operands. ­ AB+, CD­, PF*… all are examples of postfix or notations notations. ­ Like prefix notations, they are also parentheses’ free. reverse polish 2­Nov­19 Jahangir Alam 18

  19. How Computer Evaluates Expressions? • Expressions are represented in infix notations and use of parentheses is very common. • Computer may apply the operators precedence and parentheses’ rules expression. • But, this process is not feasible in terms of computer timing (timing complexity) as computer takes a lot of time to resolve parentheses’. • So, the computer first So, the computer first expression into an equivalent postfix expression and then evaluates it. • Following figure depicts the process: and evaluate the converts converts an an infix infix 2­Nov­19 Jahangir Alam 19

  20. Postfix Postfix Expression Expression Infix Infix Value of Value of Expression Expression Expression Expression • Clearly following two procedures (algorithms) are required: ­ Algorithm 1: Converting an infix expression to an equivalent postfix expression. ­ Algorithm 2: Evaluating the postfix expression. Algorithm Evaluating • For each algorithm, Stack is the main tool to be utilized. • We shall discuss Algorithm 2 first. postfix expression 2­Nov­19 Jahangir Alam 20

  21. Algorithm: Infix to Postfix Conversion • Following algorithm finds the VALUE of an expression P, written in postfix notations 1. 1. Add a right parenthesis “)” at the end Add a right parenthesis “)” at the end of P [This will act as sentinel] Scan P from left to right ( repeat steps 3 and 4 for each element of P until the sentinel “)” is encountered. If an operand is encountered, put it on STACK. 4. If an operator ⊗ ⊗ is encountered then: ) and 2. 3. 2­Nov­19 Jahangir Alam 21

  22. (a)Remove the two top elements of STACK. Let A is the top element and B is next to top element. B is next-to-top element. (b) Evaluate B ⊗ ⊗ A. (c) Place the result of step (b) back on stack. [End of If structure] [End of Step 2 loop] Set VALUE equal to the top element on Set VALUE equal to the top element on STACK Exit 5. 5. 6. 2­Nov­19 Jahangir Alam 22

  23. An Example: • Evaluate expression (Commas are used to expression (Commas are used to separate the elements of P so that 5, 6, 2 are not interpreted as 562). P: 5, 6, 2, +, *, 12, 4, /, ­ the following postfix 2­Nov­19 Jahangir Alam 23

  24. Answer •Add ) to P •Scan P from left to right and look for each step at the following table, until “) ”is encountered: Steps Symbol Encountered 1. 5 2. 6 3. 2 4. + 5. * 6. 12 7. 4 8. / 9. ­ 10 ) Steps Symbol Encountered STACK 5 5, 6 5, 6, 2 5,8 40 40, 12 40, 12 40, 12, 4 40, 3 37 VALUE=37 2­Nov­19 Jahangir Alam 24

  25. Algorithm: Converting infix expression to Postfix • Let expression expression. • Besides operands and operators, Q may also contain left and right parentheses’. • Following algorithm • Following algorithm into an equivalent expression P: Q be an infix arithmetic converts converts Q Q postfix 2­Nov­19 Jahangir Alam 25

  26. 1. Push “(“ onto STACK and add “)” to the end of Q. Scan Q from left to right ( Q right ( to 6 for each element of Q until the STACK is empty. If an operand is encountered, add it to P. If a left parenthesis is encountered, push it onto STACK. If an operator ⊗ ⊗ is encountered then: (a)Repeatedly pop from STACK and add to P each operator (on the top of STACK) which has the same or higher precedence than ⊗ (b) Add (Push) ⊗ ⊗ onto STACK. [End of If Structure] ) and repeat steps 3 ) repeat steps 2. 3. 4. 5. ⊗. 2­Nov­19 Jahangir Alam 26

  27. 6. If a right parenthesis is encountered then: (a)Repeatedly pop from STACK and add to P each operator (on the top of STACK) until a operator (on left parenthesis is encountered. (b) Remove the left parenthesis. [Don’t add it to P] [End of If Structure] [End of Step 2 loop] Exit top STACK) 7. 2­Nov­19 Jahangir Alam 27

  28. An Example • Convert expression expression expression: Q: A + (B * C ­ (D / E ↑ F) * G) * H • Answer: ­ Push “(“ on to STACK and add “) ” to Q to Q Q: A + (B * C ­ (D / E ↑ F) * G) * H) ­ Refer to the following table: following into infix arithmetic postfix equivalent 2­Nov­19 Jahangir Alam 28

  29. Answer S.No. Symbol Encoun -tered STACK P 1. 1. 2. 3. 4. 5. 6. 7, 7, 8. 9. 10. 11. ( ( ( A + ( B * C C ­ ( D / A A A (, + (, +, ( (, +, ( (, +, (, * (, +, (, * (, +, (, (, +, (,­ (, +, (,­, ( (, +, (,­, ( (, +, (,­, (, / AB AB ABC ABC ABC* ABC* ABC*D ABC*D 2­Nov­19 Jahangir Alam 29

  30. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. E (, +, (,­, (, / (, +, (,­, (, /, ↑ (, +, (,­, (, /, ↑ (, +, (,­ (, +, (,­, * (, +, (,­, * (, + (, +, * (, +, * Empty ABC*DE ABC*DE ABC*DEF ABC*DEF↑/ ABC*DEF↑/ ABC*DEF↑/G ABC*DEF↑/G*­ ABC*DEF↑/G*­ ABC*DEF↑/G*­H ABC*DEF↑/G*­H*+ ↑ F ) * G ) * H ) 2­Nov­19 Jahangir Alam 30

  31. Exercise • Convert expressions expressions: (a) Q: ( ( A + B ) — C * ( D / E ) ) + F (b) Q: ( (A + B ) * D ) • Answers: (a) P: A B + C D E / * F + (a) P: A B + C D E / * ­ F + (b) P: A B + D * E F ­ ↑ following into infix arithmetic postfix equivalent ↑ (E – F) 2­Nov­19 Jahangir Alam 31

  32. Recursion • Recursion is an important phenomenon used in computer science. • Using recursion, certain Using recursion, expressed in a more elegant way. • Suppose P is a procedure containing: ­ Either a Call statement to itself ­ Or a Call statement function that may eventually result in a Call function that may eventually result in a Call statement back to function P. • Then P is referred to as a recursive procedure/ function and this process is called recursion. procedures can be procedures or a function to another procedure/ the original procedure/ 2­Nov­19 Jahangir Alam 32

  33. Well Defined Recursive Procedure • A recursive procedure/ function is said to be well defined if it has the following two properties: two properties: 1. There must be certain criteria, called the base criteria, procedure doesn’t call to itself. 2. Each time the procedure calls to itself (directly indirectly) ,it must take (directly or indirectly) ,it must take us closer to the base criteria. for which the 2­Nov­19 Jahangir Alam 33

  34. Recursive Procedures: Examples • Factorial Function: ­ We know that: ).( 1 .( !    n n n n     n n n n 2 )( n n 1 . 2 . 3 )... 3  n  !   .( 1 )! .( ).( 1 2 )! ! 1 1    ! 5 ! 5 5 ! 4 . 5 ! 4 4 3 . 5 . 4 5 !... 3 !... 5 1 . 2 . 3 . 4 . 5 4 3 2 1 120 120 ! n • A simple algorithm to find be written as follows: can 2­Nov­19 Jahangir Alam 34

  35. 1. 2. 3. 3. 4. 5. 6. FACTORIAL(N) SET FACT := 1 REPEAT STEPS 4 AND 5 WHILE N>=1 REPEAT STEPS 4 AND 5 WHILE N>=1 SET FACT := FACT*N SET N := N-1 RETURN FACT • We also know that: 0  ! 1 • With this knowledge we can easily define a recursive procedure to find FACTORIAL(N) as follows: 2­Nov­19 Jahangir Alam 35

  36. • Recursive Procedure for ! n   if 1 N N FACTORIAL 1 FACTORIAL ( N ) { Otherwise ) 1  * ( N • This following find FACTORIAL(N): leads us to design algorithm the to recursive 2­Nov­19 Jahangir Alam 36

  37. 1. 2. FACTORIAL(N) If N <= 1 then: RETURN 1 ELSE: ELSE: RETURN N*FACTORIAL(N-1) [End of If-Else structure] EXIT 3. • Above procedure because: procedure because: 1. We have a base criteria (0! = 1). 2. Each time we call FACTORIAL, it takes us closer to the base criteria. is a well defined recursive 2­Nov­19 Jahangir Alam 37

  38. Fibonacci Series • Write a recursive procedure to find the nth term (n > 0) , of following (Fibonacci) series: 0, 1, 1, 2, 3, 5, 8, 13… • We notice that: ­ Fib(1) = 0 and Fib(2) =1 ­ Fib(n) = Fib(n-1) + Fib(n-2) Fib(n) Fib(n ) Fib(n • With above knowledge, we can define the following recursive procedure for finding the nthterm of the Fibonacci series: ) 2­Nov­19 Jahangir Alam 38

  39. 1  FIB { FIB 2     n if n n ) 1  ) 1 n FIB ( ( n ) ) { ) 2  ( ( FIB FIB ( ( n n Otherwise Otherwise ) 2 1. FIB(n) 2. If n <= 2 then: RETURN n-1 ELSE: RETURN FIB(n-1)+FIB(n-2) [End of If-Else structure] EXIT 3. 2­Nov­19 Jahangir Alam 39

  40. Summation of Infinite Series • Recursion can be used to find the sum of an infinite series accuracy accuracy. • The generalized procedure is: ­ Find the nthterm of the infinite series. ­ Find (n+1)th term (Replace n by (n+1) in the nthterm). ­ Express (n+1)thterm in terms of nthterm. Express (n+1) term in terms of n ­ Keep summing the condition is met:  curretn Sum up to the desired of the infinite series term. following terms until   Sum previous 2­Nov­19 Jahangir Alam 40

  41. ­ Where, sum. • An Example: Find the sum of the following • An Example: Find the sum of the following infinite series correct decimal (i.e. desired accuracy is .001 or less): stands for the accuracy desired in to three places of 3 5 7 x ! 3 x ! 5 x 7       x ... ... ! 2­Nov­19 Jahangir Alam 41

  42. Solution: • Step 1: nth term of given series: ) 1  ) 1  ( ( 2 2 n n x ) 1   ) 1  ( n T ( n ) (  2 ( n 1 )! • Step 2: (n+1)th term of given series: ) 1  ( 2 n x  ) 1   ) 1  ( n 2 ) T ( n (  2 ( n 1 )! 2­Nov­19 Jahangir Alam 42

  43. • Step 3: Express T(n+1) in terms of T(n) ­ T(n+1) can be expressed as follows: ) 1  ( 2 n 2 2 x x x ) 1  ) 1    ) 1    ( n T ( n ( . T ( n ).    2 2 ( n 1 )! 2 ( n 1 )( 2 n ) 4 ( n 2 n ) • Step 4: To define a recursive procedure the following expression of step 3 will be utilized: 2 x ) 1    T ( n T ( n ).  2 4 ( n 2 n ) 2­Nov­19 Jahangir Alam 43

  44. • Step finding the terms of the given infinite series may now be defined as follows: { ) 1 (  5: The recursive procedure for    x if n x 0 T n 2  .T(n) if n 0 2  ( 4 n 2 n ) 2­Nov­19 Jahangir Alam 44

  45. Assignment • Write C programs to find the sum of following infinite series correct of following infinite series correct to three places of decimal ( (a)    3 ! 2 ! 1 ):   . 001 2 3 x x x    1 ... .... ! 2 3 4 x x x (b) (b)         x x ...... 2 3 4 2 4 6 (c) x x x      1 .... 2 ! 4 ! 6 ! 2­Nov­19 Jahangir Alam 45

  46. Towers of Hanoi • The Tower of Hanoi (also called the Tower of Brahma or Lucas' pluralized as Towers) puzzle game or puzzle. • It consists of three pegs (or poles/ rods) and a number of disks of different sizes, which can slide onto any rod. • The puzzle starts with the disks in a neat stack in ascending order of size on one peg, the smallest at the top, thus making a conical shape. • The objective of the puzzle is to move the entire stack to another peg, simple rules: Tower and a sometimes mathematical is obeying the following 2­Nov­19 Jahangir Alam 46

  47. ­ Only one disk can be moved at a time. ­ Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty peg an empty peg. ­ No larger disk may be placed on top of a smaller disk. • The following figure shows a Towers of Hanoi with 8 disks. 2­Nov­19 Jahangir Alam 47

  48. Example: • Lets try to solve Towers of Hanoi with three disks kept on peg A. • Strictly following the rules of the game • Strictly following the rules of the game, we have to move all disks from peg A to peg C. C A B 2­Nov­19 Jahangir Alam 48

  49. Solution:

  50. • We notice that with 3 disks, the puzzle can be solved in 7 moves. • In general, the number of moves required to • In general, the number of moves required to solve a Towers of Hanoi puzzle with n disks is 2n-1. • Rather than finding a separate solution for each n, we will use the technique of recursion to develop a generalized solution to the Towers of Hanoi puzzle Hanoi puzzle. • We observe that the solution to the Towers of Hanoi problem for n > 1 disks may be reduced to the following sub­problems: 2­Nov­19 Jahangir Alam 50

More Related