SlideShare ist ein Scribd-Unternehmen logo
1 von 71
CIS-122 : Data Structures
Lecture- # 2
On Stacks




Conducted by
Syed Muhammad Haroon , SE




       Pakistan Institute of Engineering & Applied Sciences
       Department of Computer & Information Sciences
Outline
  •   Revision of Lecture # 01
        Definition
        Representation of Stack
        Operations on Stack
  •   Lecture # 02
        Applications of Stack
           •   Arithmetic Expression
           •   Recursion : Factorial
           •   Quick Sort
           •   Tower of Hanoi


        Assignment
           • Stack Machines
           • Record Management
REVISION OF LECTURE #1
What is a stack?


• Ordered group of homogeneous items.
• Added to and removed from the top of the stack
• LIFO: Last In, First Out.
BASIC STACK OPERATIONS


•   Initialize the Stack.
•   Pop (delete an item)
•   Push (insert an item)
•   Status(Empty, Full, No of Item, Item at Top)
•   Clear the Stack
•   Determine Stack Size
Representation of Stacks
 • Arrays
     Fixed Size Stack
     Item, top



 • Link List
     Dynamic Stack
     Node: data, link
     Stack Header
Array Representation of stacks
      • To implement a stack, items are inserted and
        removed at the same end (called the top)

      • To use an array to implement a stack, you need
        both the array itself and an integer
          The integer tells you either:
             • Which location is currently the top of the stack, or
             • How many elements are in the stack




7
Pushing and popping
  • To add (push) an element, either:
      Increment top and store the element in stk[top], or
      Store the element in stk[count] and increment count



  • To remove (pop) an element, either:
      Get the element from stk[top] and decrement top, or
      Decrement count and get the element in stk[count]
Linked-list implementation of stacks


        •    Since all the action happens at the top of a stack, a singly-linked list
             (SLL) is a fine way to implement it
        •    The header of the list points to the top of the stack



    myStack:


                              44             97             23             17



    •       Pushing is inserting an element at the front of the list
    •       Popping is removing an element from the front of the list

9
Linked-list implementation details

     •    With a linked-list representation, overflow will not happen (unless
          you exhaust memory, which is another kind of problem)

     •    Underflow can happen, and should be handled the same way as
          for an array implementation

     •    When a node is popped from a list, and the node references an
          object, the reference (the pointer in the node) does not need to be
          set to null
            Unlike an array implementation, it really is removed--you can no longer
             get to it from the linked list
            Hence, garbage collection can occur as appropriate




10
EVALUATION OF ARITHMETIC
      EXPRESSION
Building an Arithmetic Expression Evaluator
 Infix and Postfix Expressions:                  Assume 1-digit integer operands and
                                                 the binary operators + - * / only

     Infix Expression Properties:
                Usual precedence and associativity of operators
                Parentheses used to subvert precedence

     Postfix Expression Properties:
              Both operands of binary operators precede operator
              Parentheses no longer needed

       Infix Expression                  Equivalent Postfix Expression
        3*4+5                           34*5+
        3*(4+5)/2                       345+*2/
        (3+4)/(5-2)                     34+52-/
        7-(2*3+5)*(8-4/2)               723*5+842/-*-
        3-2+1                           32-1+
Building an Arithmetic Expression Evaluator
                                                        Assume 1-digit integer operands,
 Postfix Expression String Processing                   the binary operators + - * / only,
                                                        and the string to be evaluated is
                                                        properly formed
 Rules for processing the postfix string:
  Starting from the left hand end, inspect each character of the string
     1. if it’s an operand – push it on the stack
    2. if it’s an operator – remove the top 2 operands from the stack,
        perform the indicated operation, and push the result on the stack

  An Example: 3*(4+5)/2  345+*2/  13
     Remaining Postfix String  int Stack (top)       Rule Used
        345+*2/                 empty
        45+*2/                  3                       1
        5+*2/                   34                      1
        +*2/                    345                     1
        *2/                     39                      2
        2/                      27                      2
        /                       27 2                    1
        null                    13                      2
                                      value of expression at top of stack
Building an Arithmetic Expression Evaluator
 Infix to Postfix Conversion
                                                          Assume 1-digit integer operands,
                                                          the binary operators + - * / only,
                                                          and the string to be converted is
                                                          properly formed
 Rules for converting the infix string:
  Starting from the left hand end, inspect each character of the string
    1. if it’s an operand – append it to the postfix string
    2. if it’s a ‘(‘ – push it on the stack
    3. if it’s an operator – if the stack is empty, push it on the stack else pop operators o
        greater or equal precedence and append them to the postfix string, stopping whe
         a ‘(‘ is reached, an operator of lower precedence is reached, or the stack is emp
         then push the operator on the stack
    4. if it’s a ‘)’ – pop operators off the stack, appending them to the postfix string, until
        a ‘(‘ is encountered and pop the ‘(‘ off the stack
    5. when the end of the infix string is reached – pop any remaining operators off the
       stack and append them to the postfix string
Infix to Postfix Conversion (continued)
An Example: 7-(2*3+5)*(8-4/2)  723*5+842/-*-
   Remaining Infix String   char Stack Postfix String   Rule Used
    7-(2*3+5)*(8-4/2)        empty     null
    -(2*3+5)*(8-4/2)         empty     7                 1
    (2*3+5)*(8-4/2)          -         7                 3
    2*3+5)*(8-4/2)           -(        7                 2
    *3+5)*(8-4/2)            -(        72                1
    3+5)*(8-4/2)             -(*       72                3
    +5)*(8-4/2)              -(*       723               3
    5)*(8-4/2)               -(+       723*              3
    )*(8-4/2)                -(+       723*5             1
    *(8-4/2)                 -         723*5+            4
    (8-4/2)                  -*        723*5+            3
    8-4/2)                   -*(       723*5+            2
    -4/2)                    -*(       723*5+8           1
    4/2)                     -*(-      723*5+8           3
    /2)                      -*(-      723*5+84          1
    2)                       -*(-/     723*5+84          3
    )                        -*(-/     723*5+842         1
    null                       empty   723*5+842/-*-    4&5
RECURSION OR FACTORIAL
     CALCULATION
Recursion
• A recursive definition is when something is defined partly
  in terms of itself
• Here’s the mathematical definition of factorial:
                              1, if n <= 1
         factorial(n) =       n * factorial(n – 1) otherwise



• Here’s the programming definition of factorial:
     static int factorial(int n) {
        if (n <= 1) return 1;
        else return n * factorial(n - 1);
     }


17
Supporting recursion
       static int factorial(int n) {
          if (n <= 1) return 1;
          else return n * factorial(n - 1);
       }
     • If you call x = factorial(3), this enters the factorial
       method with n=3 on the stack
     • | factorial calls itself, putting n=2 on the stack
     • | | factorial calls itself, putting n=1 on the stack
     • | | factorial returns 1
     • | factorial has n=2, computes and returns 2*1 = 2
     • factorial has n=3, computes and returns 3*2 = 6


18
Factorial (animation 1)
     • x = factorial(3)
                             3 is put on stack as n
     • static int factorial(int n) { //n=3
          int r = 1;
          if (n <= 1) returnput on stack with value 1
                          r is r;
          else {
               r = n * factorial(n - 1);
               return r;
          }
       }
                                                                   r=1
                                  All references to r use this r

                                 All references to n use this n    n=3
                                   Now we recur with 2...
19
Factorial (animation 2)
     • r = n * factorial(n - 1);
                                   2 is put on stack as n
     • static int factorial(int n) {//n=2
          int r = 1;
          if (n <= 1) returnput on stack with value 1
                          r is r;
          else {
               r = n * factorial(n - 1); Now using this r     r=1
               return r;
          }                                      And this n   n=2
       }
                                                              r=1

                                                              n=3
                                   Now we recur with 1...
20
Factorial (animation 3)
     • r = n * factorial(n - 1);
                                   1 is put on stack as n
     • static int factorial(int n) {
                                                              r=1
                                          Now using this r
          int r = 1;
          if (n <= 1) return r; stack with value 1 And
                         r is put on
                                                              n=1
                                                    this n
          else {
               r = n * factorial(n - 1);                      r=1
               return r;
          }                                                   n=2
       }
                                                              r=1
                                 Now we pop r and n off the
                                 stack and return 1 as
                                                              n=3
                                 factorial(1)
21
Factorial (animation 4)
     • r = n * factorial(n - 1);


     • static int factorial(int n) {
                                                             r=1
                                         Now using this r
          int r = 1;
          if (n <= 1) return r;                    And
                                                            fac=1
                                                             n=1
                                                   this n
          else {
               r = n * factorial(n - 1);                     r=1
               return r;
          }                                                 n=2
       }
                                                             r=1
                              Now we pop r and n off the
                              stack and return 1 as         n=3
                              factorial(1)
22
Factorial (animation 5)
     • r = n * factorial(n - 1);


     • static int factorial(int n) {
          int r = 1;
          if (n <= 1) return r;
          else {
               r = n * factorial(n - 1);          Now using this r    r=1
               return r;
          }                                                And       fac=2
                                                                      n=2
                                                           this n
       }                          1
                                                                      r=1
                                   2 * 1 is 2;
                                   Pop r and n;
                                                                     n=3
                                   Return 2
23
Factorial (animation 6)
     • x = factorial(3)


     • static int factorial(int n) {
          int r = 1;
          if (n <= 1) return r;
          else {
               r = n * factorial(n - 1);
               return r;
          }
       }                          2
                                           Now using this r    r=1
                          3 * 2 is 6;
                          Pop r and n;
                                                    And       fac=6
                                                               n=3
                                                    this n
                          Return 6
24
Stack frames

• Rather than pop variables off the stack
  one at a time, they are usually organized
  into stack frames                            r=1
• Each frame provides a set of variables
                                               n=1
  and their values
• This allows variables to be popped off all   r=1
  at once
                                               n=2
• There are several different ways stack
  frames can be implemented                    r=1

                                               n=3


25
TOWER OF HANOI
Towers of Hanoi
  • The Towers of Hanoi is a puzzle made up of three
    vertical pegs and several disks that slide on the
    pegs

  • The disks are of varying size, initially placed on
    one peg with the largest disk on the bottom with
    increasingly smaller ones on top

  • The goal is to move all of the disks from one peg
    to another under the following rules:
      We can move only one disk at a time

      We cannot move a larger disk on top of a smaller one
Towers of Hanoi




   Original Configuration   Move 1




          Move 2            Move 3
Towers of Hanoi




        Move 4       Move 5




        Move 6    Move 7 (done)
QUICK SORT
Quicksort – (1) Partition


Pivot



  0      1     2        3    4    5    6
 50     60    40    90       10   80   70




 0      1     2         0     1    2    3
 40     10   50         60   90   80   70




  ©Duane Szafron 1999                       31
Quicksort – (2) recursively sort small




 0     1      2        3    4    5    6
 50    60     40   90       10   80   70




 0    1      2         0     1    2    3
40    10     50        60   90   80   70

                                                0    1    2
            quicksort(small)                    10   40   50
 ©Duane Szafron 1999                       32
Quicksort – (3) recursively sort large




  0     1      2        3    4    5    6
 50     60    40     90      10   80   70




 0     1      2         0     1    2    3
 40    10    50         60   90   80   70

                                                 0    1    2    0    1    2    3
                   quicksort(large)              10   40   50   60   70   80   90
  ©Duane Szafron 1999                       33
Quicksort – (4) concatenate



          Original array                                  Final result

 0    1      2        3    4    5    6          0    1     2    3        4    5    6
50    60    40    90       10   80   70        10   40    50   60      70     80   90



                                                         concatenate
0    1      2         0     1    2    3
40   10     50        60   90   80   70

                                               0    1     2      0       1     2    3
                                               10   40   50      60      70   80   90
©Duane Szafron 1999                       34
In-place Partition Algorithm (1)


 • Our goal is to move one element, the pivot, to its
   correct final position so that all elements to the left of it
   are smaller than it and all elements to the right of it are
   larger than it.
 • We will call this operation partition().
 • We select the left element as the pivot.



                 lp                                           r
                 0    1    2    3    4         5   6    7    8
                60    30   10   20   40    90      70   80   50
©Duane Szafron 1999                       35
In-place Partition Algorithm (2)


 • Find the rightmost element that is smaller than the pivot
   element.
                lp                                       rr
               0      1    2    3    4    5    6    7    8
               60     30   10   20   40   90   70   80   50

    Exchange the elements and increment the
     left.
                       l                                 pr
               0      1    2    3    4    5    6    7    8
               50     30   10   20   40   90   70   80   60
©Duane Szafron 1999                       36
In-place Partition Algorithm (3)


 • Find the leftmost element that is larger than the pivot
   element.
                       l                  l              pr
               0      1    2    3    4    5    6    7    8
               50     30   10   20   40   90   70   80   60

    Exchange the elements and decrement the
     right.
                                          lp         r
               0      1    2    3    4    5    6    7    8
               50     30   10   20   40   60   70   80   90
©Duane Szafron 1999                       37
In-place Partition Algorithm (4)


 • Find the rightmost element that is smaller than the pivot
   element.
                                      r   lp         r
               0      1    2    3    4    5    6    7    8
               50     30   10   20   40   60   70   80   90

    Since the right passes the left, there is no
     element and the pivot is the final location.


©Duane Szafron 1999                       38
ARITHMETIC EVALUATION
postfix calculation
 Stack
                  Postfix Expression
                      6523+8*+3+*



                         =
postfix calculation
 Stack
                  Postfix Expression
                      523+8*+3+*



                         =


    6
postfix calculation
    Stack
                 Postfix Expression
                 23+8*+3+*




      5
      6
postfix calculation
 Stack
                  Postfix Expression
                      3+8*+3+*



                         =
    2
    5
    6
postfix calculation
 Stack
                  Postfix Expression
                      +8*+3+*


    3
                         =
    2
    5
    6
postfix calculation
 Stack
                  Postfix Expression

                      8*+3+*


    3
                       +   =
    2
    5
    6
postfix calculation
 Stack
                  Postfix Expression
                      8*+3+*



    2                  +3=
    -5
    (6
postfix calculations
 Stack
                  Postfix Expression
                   8*+3+*



                   2+3=

    -5
    (6
postfix calculations
 Stack
                  Postfix Expression
                   8–( 3
                   d * + e + f* )



                   ab+c-
                   2+3=5

    -5
    *
    (6
postfix calculations
 Stack
                  Postfix Expression
                   –(+3+
                   8 * e + f )*



                   ab+c-d
                      =
    5
    -5
    *
    (6
postfix calculations
 Stack
                  Postfix Expression
                   –( 3
                   * e e f )f* )
                   ( ++ +


    8
                   a b + c –d *
                         =- d
    5
    -5
    *
    -6
    (
postfix calculations
 Stack
                  Postfix Expression
                   –3+
                   +e e )*)f )
                   ( ( ff
                   e ++ +


    8
                   a b + = –d *
                     * c- d
    5
    (5
    -
    *
    -6
    (
postfix calculations
 Stack
                  Postfix Expression
                   – 3+
                   +e )++)f )
                   ( ( e f*
                     f



                   a b 8 = –d * e
                     * +c- d
    5
    (5
    -
    *
    -6
    (
postfix calculations
 Stack
                  Postfix Expression
                   –
                   +)( e +)f )
                   ( 3+
                   f e + f*



                   a b 8 = –d * e
                   5* +c- d
    +
    (5
    -
    *
    -6
    (
postfix calculations
 Stack
                  Postfix Expression
                   –
                   +e e +)f )
                   ( 3+
                   ) ( + f*



                   5 * + c –d
                   a b 8 = 40d * e f
                           -
    +
    (5
    -
    *
    -6
    (
postfix calculations
 Stack
                  Postfix Expression
                   –3+
                   +e e +)f )
                   ( ( + f*



                   a b + c –d * e f +
                         =- d
   40
    -5
    *
    -6
    (
postfix calculations
 Stack
                  Postfix Expression
                   –( *
                   3 e e +)f )
                   ( ++ f



                   a b + c –d * e f + -
                     + =- d
   40
    -5
    *
    -6
    (
Stack
        Postfix Expression
        –( *
        3 e e +)f )
        ( ++ f



          + 40 – d
        a b + c= d * e f +
               -

  -5
  *
  -6
  (
Stack
        Postfix Expression
        – ++ f
        3( *
        ( e e +)f )



        5 + 40 – d
        a b + c= d * e f +
               -

  -
  *
  -6
  (
Stack
        Postfix Expression
        – ++ f
        3( *
        ( e e +)f )



        5 + 40 – 45
        a b + c= d * e f +
               -d

  -
  *
  -6
  (
Stack
        Postfix Expression
        –( *
        3 e e +)f )
        ( ++ f



        a b + c –d * e f +
               =- d

  -18
   45
  *
  -6
  (
Stack
        Postfix Expression
        –( *
        +*
        3 e e +)f )
        ( ++ f



        a b + c –d * e f +
               =- d
  3
  -18
   45
  *
  -6
  (
Stack
        Postfix Expression
        –( *
        *
        3 e e +)f )
        ( ++ f



        a b + c –d * e f +
          + =- d
  3
  -18
   45
  *
  -6
  (
Stack
        Postfix Expression
        –( *
        *
        3 e e +)f )
        ( ++ f



        a b + c –d * e f +
          + 3 =- d

  -18
   45
  *
  -6
  (
Stack
        Postfix Expression
        –( *
        *
        3 e e +)f )
        ( ++ f



        45 c – d
        a b + 3 =d * e f +
                -

  -18
  *
  -6
  (
Stack
        Postfix Expression
        –( *
        *
        3 e e +)f )
        ( ++ f



        45 c – 48
        a b + 3 =d * e f +
                -d

  -18
  *
  -6
  (
Stack
        Postfix Expression
        –( *
        *
        3 e e +)f )
        ( ++ f



               –d
        a b + c= d * e f +
               -

  -18
  48
  *
  -6
  (
Stack
        Postfix Expression
        – ++ f
        3( *
        ( e e +)f )



        a b + c=– d * e f +
                -d
          *

  -18
  48
  *
  -6
  (
Stack
        Postfix Expression
        – ++ f
        3( *
        ( e e +)f )



        a b + c –d * e f +
          * 48 - d
                =

  -18
  *
  -6
  (
Stack
        Postfix Expression
        –(+f
        3+*
        ( e e +)f )



        a b + c –d * e f +
        6 * 48 - d
                =

  -18
  *
  -6
  (
Stack
        Postfix Expression
        – ++ f
        3( *
        ( e e +)f )



        a b + c –d * e f +
        6 * 48 - d
                = 288

  -18
  *
  -6
  (
Stack
        Postfix Expression
        – ++ f
        3( *
        ( e e +)f )



        a b + c –d * e f +
               =- d

  -18
 *
 -6
288
 (

Weitere ähnliche Inhalte

Was ist angesagt?

Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Raj Naik
 
Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)Self-Employed
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queueSrajan Shukla
 
Hashing Technique In Data Structures
Hashing Technique In Data StructuresHashing Technique In Data Structures
Hashing Technique In Data StructuresSHAKOOR AB
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort AlgorithmLemia Algmri
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSGokul Hari
 
Introduction to stack
Introduction to stackIntroduction to stack
Introduction to stackvaibhav2910
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arorakulachihansraj
 
Data Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListData Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListManishPrajapati78
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked ListNinad Mankar
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data StructureDharita Chokshi
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data StructureMeghaj Mallick
 

Was ist angesagt? (20)

Linked list
Linked listLinked list
Linked list
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive
 
Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)Queue AS an ADT (Abstract Data Type)
Queue AS an ADT (Abstract Data Type)
 
Heap sort
Heap sortHeap sort
Heap sort
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queue
 
single linked list
single linked listsingle linked list
single linked list
 
Hashing Technique In Data Structures
Hashing Technique In Data StructuresHashing Technique In Data Structures
Hashing Technique In Data Structures
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
 
Introduction to stack
Introduction to stackIntroduction to stack
Introduction to stack
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
 
Circular queue
Circular queueCircular queue
Circular queue
 
Data Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListData Structure and Algorithms Linked List
Data Structure and Algorithms Linked List
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Queues
QueuesQueues
Queues
 
Linked List
Linked ListLinked List
Linked List
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 

Andere mochten auch

Virtual base class
Virtual base classVirtual base class
Virtual base classTech_MX
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application Tech_MX
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Permutation & Combination
Permutation & CombinationPermutation & Combination
Permutation & CombinationPuru Agrawal
 
Permutations and combinations examples
Permutations and combinations examplesPermutations and combinations examples
Permutations and combinations examplesLeo Crisologo
 
Permutation and combination
Permutation and combinationPermutation and combination
Permutation and combinationSadia Zareen
 
Permutations & Combinations
Permutations & CombinationsPermutations & Combinations
Permutations & Combinationsrfant
 

Andere mochten auch (8)

Virtual base class
Virtual base classVirtual base class
Virtual base class
 
16 combinatroics-2
16 combinatroics-216 combinatroics-2
16 combinatroics-2
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Permutation & Combination
Permutation & CombinationPermutation & Combination
Permutation & Combination
 
Permutations and combinations examples
Permutations and combinations examplesPermutations and combinations examples
Permutations and combinations examples
 
Permutation and combination
Permutation and combinationPermutation and combination
Permutation and combination
 
Permutations & Combinations
Permutations & CombinationsPermutations & Combinations
Permutations & Combinations
 

Ähnlich wie Stacks Implementation and Examples

The concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdfThe concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdfarihantsherwani
 
Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)mailmerk
 
#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docxajoy21
 
1.4 expression tree
1.4 expression tree  1.4 expression tree
1.4 expression tree Krish_ver2
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7Kumar
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.pptmrizwan38
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developersbrweber2
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsAfaq Mansoor Khan
 
LEC 7-DS ALGO(expression and huffman).pdf
LEC 7-DS  ALGO(expression and huffman).pdfLEC 7-DS  ALGO(expression and huffman).pdf
LEC 7-DS ALGO(expression and huffman).pdfMuhammadUmerIhtisham
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxYogesh Pawar
 
Sorting algos > Data Structures & Algorithums
Sorting algos  > Data Structures & AlgorithumsSorting algos  > Data Structures & Algorithums
Sorting algos > Data Structures & AlgorithumsAin-ul-Moiz Khawaja
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++NUST Stuff
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURESUsha Mahalingam
 
Applications of stack
Applications of stackApplications of stack
Applications of stackeShikshak
 
Applicationsofstack 110805072322-phpapp01
Applicationsofstack 110805072322-phpapp01Applicationsofstack 110805072322-phpapp01
Applicationsofstack 110805072322-phpapp01Jay Patel
 

Ähnlich wie Stacks Implementation and Examples (20)

Applications of Stack
Applications of StackApplications of Stack
Applications of Stack
 
The concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdfThe concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdf
 
Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)
 
#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx
 
1.4 expression tree
1.4 expression tree  1.4 expression tree
1.4 expression tree
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.ppt
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developers
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
 
Stack.pptx
Stack.pptxStack.pptx
Stack.pptx
 
LEC 7-DS ALGO(expression and huffman).pdf
LEC 7-DS  ALGO(expression and huffman).pdfLEC 7-DS  ALGO(expression and huffman).pdf
LEC 7-DS ALGO(expression and huffman).pdf
 
Stack
StackStack
Stack
 
Programming Homework Help
Programming Homework Help Programming Homework Help
Programming Homework Help
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptx
 
Sorting algos > Data Structures & Algorithums
Sorting algos  > Data Structures & AlgorithumsSorting algos  > Data Structures & Algorithums
Sorting algos > Data Structures & Algorithums
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
Applicationsofstack 110805072322-phpapp01
Applicationsofstack 110805072322-phpapp01Applicationsofstack 110805072322-phpapp01
Applicationsofstack 110805072322-phpapp01
 

Kürzlich hochgeladen

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 

Kürzlich hochgeladen (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 

Stacks Implementation and Examples

  • 1. CIS-122 : Data Structures Lecture- # 2 On Stacks Conducted by Syed Muhammad Haroon , SE Pakistan Institute of Engineering & Applied Sciences Department of Computer & Information Sciences
  • 2. Outline • Revision of Lecture # 01  Definition  Representation of Stack  Operations on Stack • Lecture # 02  Applications of Stack • Arithmetic Expression • Recursion : Factorial • Quick Sort • Tower of Hanoi  Assignment • Stack Machines • Record Management
  • 4. What is a stack? • Ordered group of homogeneous items. • Added to and removed from the top of the stack • LIFO: Last In, First Out.
  • 5. BASIC STACK OPERATIONS • Initialize the Stack. • Pop (delete an item) • Push (insert an item) • Status(Empty, Full, No of Item, Item at Top) • Clear the Stack • Determine Stack Size
  • 6. Representation of Stacks • Arrays  Fixed Size Stack  Item, top • Link List  Dynamic Stack  Node: data, link  Stack Header
  • 7. Array Representation of stacks • To implement a stack, items are inserted and removed at the same end (called the top) • To use an array to implement a stack, you need both the array itself and an integer  The integer tells you either: • Which location is currently the top of the stack, or • How many elements are in the stack 7
  • 8. Pushing and popping • To add (push) an element, either:  Increment top and store the element in stk[top], or  Store the element in stk[count] and increment count • To remove (pop) an element, either:  Get the element from stk[top] and decrement top, or  Decrement count and get the element in stk[count]
  • 9. Linked-list implementation of stacks • Since all the action happens at the top of a stack, a singly-linked list (SLL) is a fine way to implement it • The header of the list points to the top of the stack myStack: 44 97 23 17 • Pushing is inserting an element at the front of the list • Popping is removing an element from the front of the list 9
  • 10. Linked-list implementation details • With a linked-list representation, overflow will not happen (unless you exhaust memory, which is another kind of problem) • Underflow can happen, and should be handled the same way as for an array implementation • When a node is popped from a list, and the node references an object, the reference (the pointer in the node) does not need to be set to null  Unlike an array implementation, it really is removed--you can no longer get to it from the linked list  Hence, garbage collection can occur as appropriate 10
  • 12. Building an Arithmetic Expression Evaluator Infix and Postfix Expressions: Assume 1-digit integer operands and the binary operators + - * / only Infix Expression Properties: Usual precedence and associativity of operators Parentheses used to subvert precedence Postfix Expression Properties: Both operands of binary operators precede operator Parentheses no longer needed Infix Expression Equivalent Postfix Expression 3*4+5 34*5+ 3*(4+5)/2 345+*2/ (3+4)/(5-2) 34+52-/ 7-(2*3+5)*(8-4/2) 723*5+842/-*- 3-2+1 32-1+
  • 13. Building an Arithmetic Expression Evaluator Assume 1-digit integer operands, Postfix Expression String Processing the binary operators + - * / only, and the string to be evaluated is properly formed Rules for processing the postfix string: Starting from the left hand end, inspect each character of the string 1. if it’s an operand – push it on the stack 2. if it’s an operator – remove the top 2 operands from the stack, perform the indicated operation, and push the result on the stack An Example: 3*(4+5)/2  345+*2/  13 Remaining Postfix String int Stack (top) Rule Used 345+*2/ empty 45+*2/ 3 1 5+*2/ 34 1 +*2/ 345 1 *2/ 39 2 2/ 27 2 / 27 2 1 null 13 2 value of expression at top of stack
  • 14. Building an Arithmetic Expression Evaluator Infix to Postfix Conversion Assume 1-digit integer operands, the binary operators + - * / only, and the string to be converted is properly formed Rules for converting the infix string: Starting from the left hand end, inspect each character of the string 1. if it’s an operand – append it to the postfix string 2. if it’s a ‘(‘ – push it on the stack 3. if it’s an operator – if the stack is empty, push it on the stack else pop operators o greater or equal precedence and append them to the postfix string, stopping whe a ‘(‘ is reached, an operator of lower precedence is reached, or the stack is emp then push the operator on the stack 4. if it’s a ‘)’ – pop operators off the stack, appending them to the postfix string, until a ‘(‘ is encountered and pop the ‘(‘ off the stack 5. when the end of the infix string is reached – pop any remaining operators off the stack and append them to the postfix string
  • 15. Infix to Postfix Conversion (continued) An Example: 7-(2*3+5)*(8-4/2)  723*5+842/-*- Remaining Infix String char Stack Postfix String Rule Used 7-(2*3+5)*(8-4/2) empty null -(2*3+5)*(8-4/2) empty 7 1 (2*3+5)*(8-4/2) - 7 3 2*3+5)*(8-4/2) -( 7 2 *3+5)*(8-4/2) -( 72 1 3+5)*(8-4/2) -(* 72 3 +5)*(8-4/2) -(* 723 3 5)*(8-4/2) -(+ 723* 3 )*(8-4/2) -(+ 723*5 1 *(8-4/2) - 723*5+ 4 (8-4/2) -* 723*5+ 3 8-4/2) -*( 723*5+ 2 -4/2) -*( 723*5+8 1 4/2) -*(- 723*5+8 3 /2) -*(- 723*5+84 1 2) -*(-/ 723*5+84 3 ) -*(-/ 723*5+842 1 null empty 723*5+842/-*- 4&5
  • 16. RECURSION OR FACTORIAL CALCULATION
  • 17. Recursion • A recursive definition is when something is defined partly in terms of itself • Here’s the mathematical definition of factorial: 1, if n <= 1 factorial(n) = n * factorial(n – 1) otherwise • Here’s the programming definition of factorial: static int factorial(int n) { if (n <= 1) return 1; else return n * factorial(n - 1); } 17
  • 18. Supporting recursion static int factorial(int n) { if (n <= 1) return 1; else return n * factorial(n - 1); } • If you call x = factorial(3), this enters the factorial method with n=3 on the stack • | factorial calls itself, putting n=2 on the stack • | | factorial calls itself, putting n=1 on the stack • | | factorial returns 1 • | factorial has n=2, computes and returns 2*1 = 2 • factorial has n=3, computes and returns 3*2 = 6 18
  • 19. Factorial (animation 1) • x = factorial(3) 3 is put on stack as n • static int factorial(int n) { //n=3 int r = 1; if (n <= 1) returnput on stack with value 1 r is r; else { r = n * factorial(n - 1); return r; } } r=1 All references to r use this r All references to n use this n n=3 Now we recur with 2... 19
  • 20. Factorial (animation 2) • r = n * factorial(n - 1); 2 is put on stack as n • static int factorial(int n) {//n=2 int r = 1; if (n <= 1) returnput on stack with value 1 r is r; else { r = n * factorial(n - 1); Now using this r r=1 return r; } And this n n=2 } r=1 n=3 Now we recur with 1... 20
  • 21. Factorial (animation 3) • r = n * factorial(n - 1); 1 is put on stack as n • static int factorial(int n) { r=1 Now using this r int r = 1; if (n <= 1) return r; stack with value 1 And r is put on n=1 this n else { r = n * factorial(n - 1); r=1 return r; } n=2 } r=1 Now we pop r and n off the stack and return 1 as n=3 factorial(1) 21
  • 22. Factorial (animation 4) • r = n * factorial(n - 1); • static int factorial(int n) { r=1 Now using this r int r = 1; if (n <= 1) return r; And fac=1 n=1 this n else { r = n * factorial(n - 1); r=1 return r; } n=2 } r=1 Now we pop r and n off the stack and return 1 as n=3 factorial(1) 22
  • 23. Factorial (animation 5) • r = n * factorial(n - 1); • static int factorial(int n) { int r = 1; if (n <= 1) return r; else { r = n * factorial(n - 1); Now using this r r=1 return r; } And fac=2 n=2 this n } 1 r=1 2 * 1 is 2; Pop r and n; n=3 Return 2 23
  • 24. Factorial (animation 6) • x = factorial(3) • static int factorial(int n) { int r = 1; if (n <= 1) return r; else { r = n * factorial(n - 1); return r; } } 2 Now using this r r=1 3 * 2 is 6; Pop r and n; And fac=6 n=3 this n Return 6 24
  • 25. Stack frames • Rather than pop variables off the stack one at a time, they are usually organized into stack frames r=1 • Each frame provides a set of variables n=1 and their values • This allows variables to be popped off all r=1 at once n=2 • There are several different ways stack frames can be implemented r=1 n=3 25
  • 27. Towers of Hanoi • The Towers of Hanoi is a puzzle made up of three vertical pegs and several disks that slide on the pegs • The disks are of varying size, initially placed on one peg with the largest disk on the bottom with increasingly smaller ones on top • The goal is to move all of the disks from one peg to another under the following rules:  We can move only one disk at a time  We cannot move a larger disk on top of a smaller one
  • 28. Towers of Hanoi Original Configuration Move 1 Move 2 Move 3
  • 29. Towers of Hanoi Move 4 Move 5 Move 6 Move 7 (done)
  • 31. Quicksort – (1) Partition Pivot 0 1 2 3 4 5 6 50 60 40 90 10 80 70 0 1 2 0 1 2 3 40 10 50 60 90 80 70 ©Duane Szafron 1999 31
  • 32. Quicksort – (2) recursively sort small 0 1 2 3 4 5 6 50 60 40 90 10 80 70 0 1 2 0 1 2 3 40 10 50 60 90 80 70 0 1 2 quicksort(small) 10 40 50 ©Duane Szafron 1999 32
  • 33. Quicksort – (3) recursively sort large 0 1 2 3 4 5 6 50 60 40 90 10 80 70 0 1 2 0 1 2 3 40 10 50 60 90 80 70 0 1 2 0 1 2 3 quicksort(large) 10 40 50 60 70 80 90 ©Duane Szafron 1999 33
  • 34. Quicksort – (4) concatenate Original array Final result 0 1 2 3 4 5 6 0 1 2 3 4 5 6 50 60 40 90 10 80 70 10 40 50 60 70 80 90 concatenate 0 1 2 0 1 2 3 40 10 50 60 90 80 70 0 1 2 0 1 2 3 10 40 50 60 70 80 90 ©Duane Szafron 1999 34
  • 35. In-place Partition Algorithm (1) • Our goal is to move one element, the pivot, to its correct final position so that all elements to the left of it are smaller than it and all elements to the right of it are larger than it. • We will call this operation partition(). • We select the left element as the pivot. lp r 0 1 2 3 4 5 6 7 8 60 30 10 20 40 90 70 80 50 ©Duane Szafron 1999 35
  • 36. In-place Partition Algorithm (2) • Find the rightmost element that is smaller than the pivot element. lp rr 0 1 2 3 4 5 6 7 8 60 30 10 20 40 90 70 80 50  Exchange the elements and increment the left. l pr 0 1 2 3 4 5 6 7 8 50 30 10 20 40 90 70 80 60 ©Duane Szafron 1999 36
  • 37. In-place Partition Algorithm (3) • Find the leftmost element that is larger than the pivot element. l l pr 0 1 2 3 4 5 6 7 8 50 30 10 20 40 90 70 80 60  Exchange the elements and decrement the right. lp r 0 1 2 3 4 5 6 7 8 50 30 10 20 40 60 70 80 90 ©Duane Szafron 1999 37
  • 38. In-place Partition Algorithm (4) • Find the rightmost element that is smaller than the pivot element. r lp r 0 1 2 3 4 5 6 7 8 50 30 10 20 40 60 70 80 90  Since the right passes the left, there is no element and the pivot is the final location. ©Duane Szafron 1999 38
  • 40. postfix calculation Stack Postfix Expression 6523+8*+3+* =
  • 41. postfix calculation Stack Postfix Expression 523+8*+3+* = 6
  • 42. postfix calculation Stack Postfix Expression 23+8*+3+* 5 6
  • 43. postfix calculation Stack Postfix Expression 3+8*+3+* = 2 5 6
  • 44. postfix calculation Stack Postfix Expression +8*+3+* 3 = 2 5 6
  • 45. postfix calculation Stack Postfix Expression 8*+3+* 3 + = 2 5 6
  • 46. postfix calculation Stack Postfix Expression 8*+3+* 2 +3= -5 (6
  • 47. postfix calculations Stack Postfix Expression 8*+3+* 2+3= -5 (6
  • 48. postfix calculations Stack Postfix Expression 8–( 3 d * + e + f* ) ab+c- 2+3=5 -5 * (6
  • 49. postfix calculations Stack Postfix Expression –(+3+ 8 * e + f )* ab+c-d = 5 -5 * (6
  • 50. postfix calculations Stack Postfix Expression –( 3 * e e f )f* ) ( ++ + 8 a b + c –d * =- d 5 -5 * -6 (
  • 51. postfix calculations Stack Postfix Expression –3+ +e e )*)f ) ( ( ff e ++ + 8 a b + = –d * * c- d 5 (5 - * -6 (
  • 52. postfix calculations Stack Postfix Expression – 3+ +e )++)f ) ( ( e f* f a b 8 = –d * e * +c- d 5 (5 - * -6 (
  • 53. postfix calculations Stack Postfix Expression – +)( e +)f ) ( 3+ f e + f* a b 8 = –d * e 5* +c- d + (5 - * -6 (
  • 54. postfix calculations Stack Postfix Expression – +e e +)f ) ( 3+ ) ( + f* 5 * + c –d a b 8 = 40d * e f - + (5 - * -6 (
  • 55. postfix calculations Stack Postfix Expression –3+ +e e +)f ) ( ( + f* a b + c –d * e f + =- d 40 -5 * -6 (
  • 56. postfix calculations Stack Postfix Expression –( * 3 e e +)f ) ( ++ f a b + c –d * e f + - + =- d 40 -5 * -6 (
  • 57. Stack Postfix Expression –( * 3 e e +)f ) ( ++ f + 40 – d a b + c= d * e f + - -5 * -6 (
  • 58. Stack Postfix Expression – ++ f 3( * ( e e +)f ) 5 + 40 – d a b + c= d * e f + - - * -6 (
  • 59. Stack Postfix Expression – ++ f 3( * ( e e +)f ) 5 + 40 – 45 a b + c= d * e f + -d - * -6 (
  • 60. Stack Postfix Expression –( * 3 e e +)f ) ( ++ f a b + c –d * e f + =- d -18 45 * -6 (
  • 61. Stack Postfix Expression –( * +* 3 e e +)f ) ( ++ f a b + c –d * e f + =- d 3 -18 45 * -6 (
  • 62. Stack Postfix Expression –( * * 3 e e +)f ) ( ++ f a b + c –d * e f + + =- d 3 -18 45 * -6 (
  • 63. Stack Postfix Expression –( * * 3 e e +)f ) ( ++ f a b + c –d * e f + + 3 =- d -18 45 * -6 (
  • 64. Stack Postfix Expression –( * * 3 e e +)f ) ( ++ f 45 c – d a b + 3 =d * e f + - -18 * -6 (
  • 65. Stack Postfix Expression –( * * 3 e e +)f ) ( ++ f 45 c – 48 a b + 3 =d * e f + -d -18 * -6 (
  • 66. Stack Postfix Expression –( * * 3 e e +)f ) ( ++ f –d a b + c= d * e f + - -18 48 * -6 (
  • 67. Stack Postfix Expression – ++ f 3( * ( e e +)f ) a b + c=– d * e f + -d * -18 48 * -6 (
  • 68. Stack Postfix Expression – ++ f 3( * ( e e +)f ) a b + c –d * e f + * 48 - d = -18 * -6 (
  • 69. Stack Postfix Expression –(+f 3+* ( e e +)f ) a b + c –d * e f + 6 * 48 - d = -18 * -6 (
  • 70. Stack Postfix Expression – ++ f 3( * ( e e +)f ) a b + c –d * e f + 6 * 48 - d = 288 -18 * -6 (
  • 71. Stack Postfix Expression – ++ f 3( * ( e e +)f ) a b + c –d * e f + =- d -18 * -6 288 (