SlideShare a Scribd company logo
1 of 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
 (

More Related Content

What's hot

Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
ghhgj jhgh
 

What's hot (20)

Linked list
Linked listLinked list
Linked list
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 
stack & queue
stack & queuestack & queue
stack & queue
 
Queue - Data Structure - Notes
Queue - Data Structure - NotesQueue - Data Structure - Notes
Queue - Data Structure - Notes
 
single linked list
single linked listsingle linked list
single linked list
 
Stack_Data_Structure.pptx
Stack_Data_Structure.pptxStack_Data_Structure.pptx
Stack_Data_Structure.pptx
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 
Circular queue
Circular queueCircular queue
Circular queue
 
Linked list
Linked listLinked list
Linked list
 
Arrays In C++
Arrays In C++Arrays In C++
Arrays In C++
 
Stack
StackStack
Stack
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search tree
 
Linked list
Linked listLinked list
Linked list
 
Stacks in Data Structure
Stacks in Data StructureStacks in Data Structure
Stacks in Data Structure
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
Stack
StackStack
Stack
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 

Viewers also liked (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
 

Similar to 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 .pdf
arihantsherwani
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
Kumar
 
Sorting algos > Data Structures & Algorithums
Sorting algos  > Data Structures & AlgorithumsSorting algos  > Data Structures & Algorithums
Sorting algos > Data Structures & Algorithums
Ain-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.pdf
ARCHANASTOREKOTA
 
Applicationsofstack 110805072322-phpapp01
Applicationsofstack 110805072322-phpapp01Applicationsofstack 110805072322-phpapp01
Applicationsofstack 110805072322-phpapp01
Jay Patel
 

Similar to 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
 
Applicationsofstack 110805072322-phpapp01
Applicationsofstack 110805072322-phpapp01Applicationsofstack 110805072322-phpapp01
Applicationsofstack 110805072322-phpapp01
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 

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 (