SlideShare una empresa de Scribd logo
1 de 26
IMPLEMENTATION OF STACKS
        PART 1
INTRODUCTION ABOUT STACKS
The stack is a very common data structure used in programs which has
lot of potential.
 Stacks hold objects, usually all of the same type.
 It follows the concept of LIFO – last in first out.
 Stack is a linear list of items in which all additions and deletion are
restricted to one end.
 Some languages, like LISP and Python, do not call for stack
implementations, since push and pop functions are available for any list.
 All Forth-like languages (such as Adobe PhotoScript) are also designed
around language-defined stacks that are directly visible to and
manipulated by the programmer.
STACKS VS ARRAYS
 An array is a contiguous block of memory.
 A stack is a first-in-last-out data structure with access only to the top
of the data.
 Since many languages does not provide facility for stack, it is backed
by either arrays or linked list.
 The values can be added and deleted on any side from an array.
 But in stack, insertion and deletion is possible on only one side of the
stack. The other side is sealed.
Eg: a[10] –array                     a[10] - stack
STACK OPERATIONS
        The bottom of a stack is a sealed end. Stack may have a capacity
which is a limitation on the number of elements in a stack. The operations
on stack are
    •Push: Places an object on the top of the stack.
    • Pop: Removes an object from the top of the stack.
    • IsEmpty: Reports whether the stack is empty or not.
    • IsFull: Reports whether the stack exceeds limit or not.
                                              c
                                              b
                          a                   a
       (i)stack   (ii)push(s,a) (iii)push(s,d)-stack overflow (iv)pop(s)

                          (v)pop(s)-stack underflow
STACK OPERATIONS




           B
           E
           D
           A
A    B     C    D      E
STACK IMPLEMENTATION
 Stack   data structure is not inherently provided by many programming
languages.
 Stack is implemented using arrays or linked lists.
 Let S be a stack, n be the capacity, x be the element to be pushed, then
push and pop will be given as
                          Push(S,x) and Pop(S)
 Here we use “top” which keeps track of the top element in the stack.
 When top = = 0 , and pop() operation gives stack underflow as result.
 When top = = n, and push() operation gives stack overflow as result.
 The pop() operation just gives an illusion of deletion, but the elements
are retained. Only the top is decremented.
S[1:6]                                Pop(S)   a   b     c   d
                                                 e                   Top=5


Push(S,a) a                             Pop(S) a
                                        Pop(S)     Top=1
              Top=1                     Pop(S)
                                        Pop(S) pop(S)
Push(S,a) a b c             d   e   f
Push(S,b)
Push(S,c) push(S,d)         Top=6       Pop(S)
Push(S,e) push(S,f)                          Top=0


Push(S,g) a     b      c    d   e   f   Pop(S)
                      Top=6 = n              Top=0 stack underflow
                      Stack overflow
STACK APPLICATIONS
 Recursion handling
 Evaluation of expression
      Conversion of infix to postfix expression
      Computation of postfix expression
 Parenthesis handling
 Backtracking
      Conversion of decimal to other number system
      Maze tracer
      Undo operations
RECURSION HANDLING
 Without stack, recursion is difficult
 Compiler automatically uses stack data structure while handling
   recursion.
 All computer needs to remember for each active function call, values
   of arguments & local variables and the location of the next statement
   to be executed when control goes back.
 Essentially what is happening when we call that method is that our
   current execution point is pushed onto the call stack and the runtime
   starts executing the code for the internal method call. When that
   method finally returns, we pop our place from the stack and continue
   executing.
Eg: int f(int n)
        { int k,r;
          if(n==0) return 0;
          k=n*n;
          r=f(n-1);
        Return k+r;
        }

    n     3                    3     3 2             3 2 1
          -                    9     9 4             9 4 1
    k
    r     -                    .     . .             . . .




n        3 2 1                 3 2   3
         9 4 1                 9 4   9
k
r        . . 0                 . 1   5



                                           Ans: 14
PARENTHESIS CHECKING
Procedure check()
  Declare a character stack S.
  Now traverse the expression.
     a) If the current character is a starting bracket then push it to
       stack.
     b) If the current character is a closing bracket then pop from
       stack and if the popped character is the matching starting bracket
       then fine else parenthesis are not balanced.
  After complete traversal, if there is some starting bracket left in stack
then “not balanced”
End procedure
Eg: [a+(b*c)+{(d-e)}]


[                             Push [

[ (                           Push (

[                             ) and ( matches, Pop (

[ {                           Push {

[ { (                         Push (

                              matches, pop (
[ {

[                             Matches, pop {

                              Matches, pop [


                              Thus, parenthesis match here
CONVERSION OF INFIX TO POSTFIX
 Expressions can be represented in prefix, postfix or infix notations.
 Conversion from one form of the expression to another form may be
accomplished using a stack.
We do not know what to do if an operator is read as an input character.
By implementing the priority rule for operators, we have a solution to this
problem.
The Priority rule: we should perform comparative priority check if an
operator is read, and then push it. If the stack top contains an operator of
priority higher than or equal to the priority of the input operator, then we
pop it and print it. We keep on performing the priority check until the top
of stack either contains an operator of lower priority or if it does not
contain an operator.
Eg: (A*B)+C

Element               Stack          Prefix         Action

  $           $                               Work stack

  (           $   (                           Push (

  A           $   (           A               Print A

  *           $   (    *                      Push(*)

  B           $   (    *      AB              Print B

  )           $               AB*             Pop *,( print *

  +           $   +                           Push +

  C           $   +           AB*C            Print C

  $                           AB*C+           Pop +
EVALUATION OF POSTFIX EXPRESSION
 Postfix expression is easily evaluated by the compiler by using stack.
 The procedure for the evaluation of postfix expression is given below:
procedure eval(E)
        x=getnextchar(E);
        case x:
                  x is an operand: push x into stack S.
                  x is an operator: pop elements, perform operation and
                          push result into stack.
                  x is null: pop stack and print result
        end case
End procedure
Eg: AB*C+   A=2, B=3, C=5



        Element                 Stack         Action
       A                                Push A
                          A
       B                                Push B
                          A B
       *                  6             Pop A and B, A*B,
                                        push 6

       C                  6 C           Push C

       +                  11            Pop C and 6,
                                        C+6, push 11
       $
                                        Pop

              Result:11
BACKTRACKING
Backtracking is a simple, elegant, recursive technique which can be put to a
variety of uses.
 You start at the root of a tree, the tree probably has some good and bad
leaves. You want to get to a good leaf. At each node, you choose one of its
children to move to, and you keep this up in a stack until you get to a leaf.
 Suppose you get to a bad leaf. You can backtrack to continue the search for
a good leaf by revoking your most recent choice, and trying out the next
option in that set of options.
 If you run out of options, revoke the choice that got you here, and try
another choice at that node.
 If you end up at the root with no options left, there are no good leaves to be
found.
Eg:




•Starting at Root, your options are A and B. You choose A.
•At A, your options are C and D. You choose C.
•C is bad. Go back to A.
•At A, you have already tried C, and it failed. Try D.
•D is bad. Go back to A.
•At A, you have no options left to try. Go back to Root.
•At Root, you have already tried A. Try B.
•At B, your options are E and F. Try E.
•E is good.
CONVERSION OF DECIMAL TO OTHER NUMBER SYSTEM

 The given decimal number is divided by the base (2 or 8 or 16)
 repeatedly and the corresponding remainders are pushed into stack.
 At last the elements are popped out of the stack to give the result.


                 Eg. 84 – 1010100 in binary
                           124 in octal
                            54 in hexadecimal
84 / 2 = 42   0           1
42 / 2 = 21   0               pop   1010100
                          0
21 / 2 = 10   1
10 / 2 = 5    0           1
5/2=2         1           0
2/2=1         0
                          1
              1
                          0
                  push    0


84 / 8 = 10   4
10 / 8 = 1    2           1   pop   124
              1           2
                  push    4


84 / 16 = 5   4
              5           5
                   push       pop 54
                          4
MAZE TRACER
        All our mazes will be two-dimensional arrays of n rows and n
columns. Each row, column cell is either open, or blocked by an internal
wall. From any open cell, you may move left, right, up, or down to an
adjacent empty cell. To solve a maze, you must find a path of open cells
from a given start cell to a specified end cell. By default, you should
assume that the start cell is in position (0,0).
            Sample:
            SOOOOO
            HHHHOH
            HOOOOH
            HOHHHH
            HOHOOO
            HOOOHE

  The path will be: [(0,0),(0,1),(0,2),(0,3),(0,4), (1,4),(2,4),(2,3), (2,2),(2,1),(3,1),
  (4,1),(5,1),(5,2),(5,3),(4,3),(4,4), (4,5),(5,5)]
SOOOOO
HHHHOH
HOOOOH
HOHHHH
HOHOOO
HOOOHE


                                                   2   4
                   0   5                1   4      1   4
                   0   4      0     4   0   4      0   4
   0       0       0      3   0     3   0      3   0      3
Push start (0,0)   0      2   0     2   0      2   0      2
                   0      1   0     1   0      1   0      1

                   0      0   0     0   0      0   0      0
                   Push       Pop       Push       Push
4      1                      5      5   End
2   1                 4      5
           3      1   4      4           4      5
2   2      2      1                      4      4
                      4      3
2   3                                    4      3
           2      2   5      3
2   4                                    5      3
           2      3   5      2
1   4                                    5      2
           2      4   5      1
0   4      1      4                      5      1
                      4      1
0      3   0      4   3      1           4      1
0      2              2      1           3      1
           0      3
0      1                                 2      1
           0      2   2      2
                      2      3           2      2
0      0   0      1
                      2      4           2      3
Push
           0      0   1      4           2      4
               Push                      1      4
                      0      4
                                         0      4
                      0      3
                      0      2           0      3
                                         0      2
                      0      1
                                         0      1
                      0      0
                                 start   0      0
                          Push
                                             Push
UNDO OPERATION
 An   undo operation is a method for reverting a change to an object,
along with the arguments needed to revert the change.
Undo operations are typically collected in undo groups, which
represent whole revertible actions, and are stored on a stack.
 To undo a single operation, it must still be packaged in a group.
 Undo groups are stored on a stack, with the oldest groups at the
bottom and the newest at the top.
 The undo stack is unlimited by default, but you can restrict it.
 When the stack exceeds the maximum, the oldest undo groups are
dropped from the bottom.
UNDO OPERATION
Initially, both stacks are empty. Recording undo operations adds to the
undo stack, but the redo stack remains empty until undo is performed.
 Performing undo causes the reverting operations in the latest group to
be applied to their objects.
Consecutive undos add to the redo stack. Subsequent redo operations
pull the operations off the redo stack, apply them to the objects, and
push them back onto the undo stack.
The redo stack’s contents last as long as undo and redo are performed
successively. However, because applying a new change to an object
invalidates the previous changes, as soon as a new undo operation is
registered, any existing redo stack is cleared.
Thank you…!

Más contenido relacionado

La actualidad más candente

Queue data structure
Queue data structureQueue data structure
Queue data structureanooppjoseph
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfixSelf-Employed
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.pptTirthika Bandi
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTUREArchie Jamwal
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTSoumen Santra
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary treeKrish_ver2
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Data Structures : hashing (1)
Data Structures : hashing (1)Data Structures : hashing (1)
Data Structures : hashing (1)Home
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Anand Ingle
 
Array data structure
Array data structureArray data structure
Array data structuremaamir farooq
 

La actualidad más candente (20)

Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Stacks
StacksStacks
Stacks
 
Stack a Data Structure
Stack a Data StructureStack a Data Structure
Stack a Data Structure
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
List in Python
List in PythonList in Python
List in Python
 
Graph traversals in Data Structures
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data Structures
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 
Linked list
Linked listLinked list
Linked list
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
class and objects
class and objectsclass and objects
class and objects
 
Data Structures : hashing (1)
Data Structures : hashing (1)Data Structures : hashing (1)
Data Structures : hashing (1)
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure
 
Array data structure
Array data structureArray data structure
Array data structure
 

Destacado

Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examplesgreatqadirgee4u
 
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
 
Permutation & Combination
Permutation & CombinationPermutation & Combination
Permutation & CombinationPuru Agrawal
 
Permutation and combination
Permutation and combinationPermutation and combination
Permutation and combinationSadia Zareen
 
Permutations and combinations examples
Permutations and combinations examplesPermutations and combinations examples
Permutations and combinations examplesLeo Crisologo
 
Permutations & Combinations
Permutations & CombinationsPermutations & Combinations
Permutations & Combinationsrfant
 

Destacado (8)

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

Similar a Stack data structure

STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxKALPANAC20
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7Kumar
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxchandankumar364348
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxhaaamin01
 
Stack - Data Structure - Notes
Stack - Data Structure - NotesStack - Data Structure - Notes
Stack - Data Structure - NotesOmprakash Chauhan
 
358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9sumitbardhan
 
Stack application
Stack applicationStack application
Stack applicationStudent
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxprakashvs7
 

Similar a Stack data structure (20)

Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
Introduction To Stack
Introduction To StackIntroduction To Stack
Introduction To Stack
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
 
PARSING.ppt
PARSING.pptPARSING.ppt
PARSING.ppt
 
Stack
StackStack
Stack
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
stack
stackstack
stack
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Stacks
StacksStacks
Stacks
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
 
Data structures
Data structures Data structures
Data structures
 
Stack - Data Structure - Notes
Stack - Data Structure - NotesStack - Data Structure - Notes
Stack - Data Structure - Notes
 
Chapter 6 ds
Chapter 6 dsChapter 6 ds
Chapter 6 ds
 
Stack
StackStack
Stack
 
358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9
 
CH4.pptx
CH4.pptxCH4.pptx
CH4.pptx
 
Stack application
Stack applicationStack application
Stack application
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
 

Más de Tech_MX

Theory of estimation
Theory of estimationTheory of estimation
Theory of estimationTech_MX
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
String & its application
String & its applicationString & its application
String & its applicationTech_MX
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2Tech_MX
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applicationsTech_MX
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2Tech_MX
 
Set data structure
Set data structure Set data structure
Set data structure Tech_MX
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating SystemTech_MX
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Tech_MX
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pcTech_MX
 
More on Lex
More on LexMore on Lex
More on LexTech_MX
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbmsTech_MX
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)Tech_MX
 
Memory dbms
Memory dbmsMemory dbms
Memory dbmsTech_MX
 
Linear regression
Linear regressionLinear regression
Linear regressionTech_MX
 
Keyboard interrupt
Keyboard interruptKeyboard interrupt
Keyboard interruptTech_MX
 

Más de Tech_MX (20)

Uid
UidUid
Uid
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
String & its application
String & its applicationString & its application
String & its application
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
 
Spss
SpssSpss
Spss
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
 
Set data structure
Set data structure Set data structure
Set data structure
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating System
 
Parsing
ParsingParsing
Parsing
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pc
 
More on Lex
More on LexMore on Lex
More on Lex
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)
 
Memory dbms
Memory dbmsMemory dbms
Memory dbms
 
Linkers
LinkersLinkers
Linkers
 
Linear regression
Linear regressionLinear regression
Linear regression
 
Keyboard interrupt
Keyboard interruptKeyboard interrupt
Keyboard interrupt
 

Último

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Stack data structure

  • 2. INTRODUCTION ABOUT STACKS The stack is a very common data structure used in programs which has lot of potential.  Stacks hold objects, usually all of the same type.  It follows the concept of LIFO – last in first out.  Stack is a linear list of items in which all additions and deletion are restricted to one end.  Some languages, like LISP and Python, do not call for stack implementations, since push and pop functions are available for any list.  All Forth-like languages (such as Adobe PhotoScript) are also designed around language-defined stacks that are directly visible to and manipulated by the programmer.
  • 3. STACKS VS ARRAYS  An array is a contiguous block of memory.  A stack is a first-in-last-out data structure with access only to the top of the data.  Since many languages does not provide facility for stack, it is backed by either arrays or linked list.  The values can be added and deleted on any side from an array.  But in stack, insertion and deletion is possible on only one side of the stack. The other side is sealed. Eg: a[10] –array a[10] - stack
  • 4. STACK OPERATIONS The bottom of a stack is a sealed end. Stack may have a capacity which is a limitation on the number of elements in a stack. The operations on stack are •Push: Places an object on the top of the stack. • Pop: Removes an object from the top of the stack. • IsEmpty: Reports whether the stack is empty or not. • IsFull: Reports whether the stack exceeds limit or not. c b a a (i)stack (ii)push(s,a) (iii)push(s,d)-stack overflow (iv)pop(s) (v)pop(s)-stack underflow
  • 5. STACK OPERATIONS B E D A A B C D E
  • 6. STACK IMPLEMENTATION  Stack data structure is not inherently provided by many programming languages.  Stack is implemented using arrays or linked lists.  Let S be a stack, n be the capacity, x be the element to be pushed, then push and pop will be given as Push(S,x) and Pop(S)  Here we use “top” which keeps track of the top element in the stack.  When top = = 0 , and pop() operation gives stack underflow as result.  When top = = n, and push() operation gives stack overflow as result.  The pop() operation just gives an illusion of deletion, but the elements are retained. Only the top is decremented.
  • 7. S[1:6] Pop(S) a b c d e Top=5 Push(S,a) a Pop(S) a Pop(S) Top=1 Top=1 Pop(S) Pop(S) pop(S) Push(S,a) a b c d e f Push(S,b) Push(S,c) push(S,d) Top=6 Pop(S) Push(S,e) push(S,f) Top=0 Push(S,g) a b c d e f Pop(S) Top=6 = n Top=0 stack underflow Stack overflow
  • 8. STACK APPLICATIONS  Recursion handling  Evaluation of expression Conversion of infix to postfix expression Computation of postfix expression  Parenthesis handling  Backtracking Conversion of decimal to other number system Maze tracer Undo operations
  • 9. RECURSION HANDLING  Without stack, recursion is difficult  Compiler automatically uses stack data structure while handling recursion.  All computer needs to remember for each active function call, values of arguments & local variables and the location of the next statement to be executed when control goes back.  Essentially what is happening when we call that method is that our current execution point is pushed onto the call stack and the runtime starts executing the code for the internal method call. When that method finally returns, we pop our place from the stack and continue executing.
  • 10. Eg: int f(int n) { int k,r; if(n==0) return 0; k=n*n; r=f(n-1); Return k+r; } n 3 3 3 2 3 2 1 - 9 9 4 9 4 1 k r - . . . . . . n 3 2 1 3 2 3 9 4 1 9 4 9 k r . . 0 . 1 5 Ans: 14
  • 11. PARENTHESIS CHECKING Procedure check() Declare a character stack S. Now traverse the expression. a) If the current character is a starting bracket then push it to stack. b) If the current character is a closing bracket then pop from stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced. After complete traversal, if there is some starting bracket left in stack then “not balanced” End procedure
  • 12. Eg: [a+(b*c)+{(d-e)}] [ Push [ [ ( Push ( [ ) and ( matches, Pop ( [ { Push { [ { ( Push ( matches, pop ( [ { [ Matches, pop { Matches, pop [ Thus, parenthesis match here
  • 13. CONVERSION OF INFIX TO POSTFIX  Expressions can be represented in prefix, postfix or infix notations.  Conversion from one form of the expression to another form may be accomplished using a stack. We do not know what to do if an operator is read as an input character. By implementing the priority rule for operators, we have a solution to this problem. The Priority rule: we should perform comparative priority check if an operator is read, and then push it. If the stack top contains an operator of priority higher than or equal to the priority of the input operator, then we pop it and print it. We keep on performing the priority check until the top of stack either contains an operator of lower priority or if it does not contain an operator.
  • 14. Eg: (A*B)+C Element Stack Prefix Action $ $ Work stack ( $ ( Push ( A $ ( A Print A * $ ( * Push(*) B $ ( * AB Print B ) $ AB* Pop *,( print * + $ + Push + C $ + AB*C Print C $ AB*C+ Pop +
  • 15. EVALUATION OF POSTFIX EXPRESSION  Postfix expression is easily evaluated by the compiler by using stack.  The procedure for the evaluation of postfix expression is given below: procedure eval(E) x=getnextchar(E); case x: x is an operand: push x into stack S. x is an operator: pop elements, perform operation and push result into stack. x is null: pop stack and print result end case End procedure
  • 16. Eg: AB*C+ A=2, B=3, C=5 Element Stack Action A Push A A B Push B A B * 6 Pop A and B, A*B, push 6 C 6 C Push C + 11 Pop C and 6, C+6, push 11 $ Pop Result:11
  • 17. BACKTRACKING Backtracking is a simple, elegant, recursive technique which can be put to a variety of uses.  You start at the root of a tree, the tree probably has some good and bad leaves. You want to get to a good leaf. At each node, you choose one of its children to move to, and you keep this up in a stack until you get to a leaf.  Suppose you get to a bad leaf. You can backtrack to continue the search for a good leaf by revoking your most recent choice, and trying out the next option in that set of options.  If you run out of options, revoke the choice that got you here, and try another choice at that node.  If you end up at the root with no options left, there are no good leaves to be found.
  • 18. Eg: •Starting at Root, your options are A and B. You choose A. •At A, your options are C and D. You choose C. •C is bad. Go back to A. •At A, you have already tried C, and it failed. Try D. •D is bad. Go back to A. •At A, you have no options left to try. Go back to Root. •At Root, you have already tried A. Try B. •At B, your options are E and F. Try E. •E is good.
  • 19. CONVERSION OF DECIMAL TO OTHER NUMBER SYSTEM The given decimal number is divided by the base (2 or 8 or 16) repeatedly and the corresponding remainders are pushed into stack. At last the elements are popped out of the stack to give the result. Eg. 84 – 1010100 in binary 124 in octal 54 in hexadecimal
  • 20. 84 / 2 = 42 0 1 42 / 2 = 21 0 pop 1010100 0 21 / 2 = 10 1 10 / 2 = 5 0 1 5/2=2 1 0 2/2=1 0 1 1 0 push 0 84 / 8 = 10 4 10 / 8 = 1 2 1 pop 124 1 2 push 4 84 / 16 = 5 4 5 5 push pop 54 4
  • 21. MAZE TRACER All our mazes will be two-dimensional arrays of n rows and n columns. Each row, column cell is either open, or blocked by an internal wall. From any open cell, you may move left, right, up, or down to an adjacent empty cell. To solve a maze, you must find a path of open cells from a given start cell to a specified end cell. By default, you should assume that the start cell is in position (0,0). Sample: SOOOOO HHHHOH HOOOOH HOHHHH HOHOOO HOOOHE The path will be: [(0,0),(0,1),(0,2),(0,3),(0,4), (1,4),(2,4),(2,3), (2,2),(2,1),(3,1), (4,1),(5,1),(5,2),(5,3),(4,3),(4,4), (4,5),(5,5)]
  • 22. SOOOOO HHHHOH HOOOOH HOHHHH HOHOOO HOOOHE 2 4 0 5 1 4 1 4 0 4 0 4 0 4 0 4 0 0 0 3 0 3 0 3 0 3 Push start (0,0) 0 2 0 2 0 2 0 2 0 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 Push Pop Push Push
  • 23. 4 1 5 5 End 2 1 4 5 3 1 4 4 4 5 2 2 2 1 4 4 4 3 2 3 4 3 2 2 5 3 2 4 5 3 2 3 5 2 1 4 5 2 2 4 5 1 0 4 1 4 5 1 4 1 0 3 0 4 3 1 4 1 0 2 2 1 3 1 0 3 0 1 2 1 0 2 2 2 2 3 2 2 0 0 0 1 2 4 2 3 Push 0 0 1 4 2 4 Push 1 4 0 4 0 4 0 3 0 2 0 3 0 2 0 1 0 1 0 0 start 0 0 Push Push
  • 24. UNDO OPERATION  An undo operation is a method for reverting a change to an object, along with the arguments needed to revert the change. Undo operations are typically collected in undo groups, which represent whole revertible actions, and are stored on a stack.  To undo a single operation, it must still be packaged in a group.  Undo groups are stored on a stack, with the oldest groups at the bottom and the newest at the top.  The undo stack is unlimited by default, but you can restrict it.  When the stack exceeds the maximum, the oldest undo groups are dropped from the bottom.
  • 25. UNDO OPERATION Initially, both stacks are empty. Recording undo operations adds to the undo stack, but the redo stack remains empty until undo is performed.  Performing undo causes the reverting operations in the latest group to be applied to their objects. Consecutive undos add to the redo stack. Subsequent redo operations pull the operations off the redo stack, apply them to the objects, and push them back onto the undo stack. The redo stack’s contents last as long as undo and redo are performed successively. However, because applying a new change to an object invalidates the previous changes, as soon as a new undo operation is registered, any existing redo stack is cleared.