You are on page 1of 16

LESSON 5: Stacks

Stack

cafeteria-tray holder

1
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

Stack Representation
 Two ways to represent a stack
 insertion, deletion, and retrieval are done from the last element in the array
(Arr[n]).
 used when the maximum size of the stack is known.

1. Doubly-Linked List Representation

2
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

Stack Operations

3
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

Example 1: Function calls


Stacks: used by computers to process function calls and their returns

4
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

Function Calls
When PROC1 begins executing, the stack will contain:

When FUNC1 is invoked by PROC1:  

5
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

Function Calls
 When FUNC1 will reference FUNC2, the stack will contain the following
information:

6
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

Function Calls
The stack will now contain:

The stack will now have the following information:

Ø Once FUNC1 has completed, the same


procedure will be performed by the system to
return processing to PROC1.

7
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

Example 2: Evaluation of Expressions


 An expression is made up of operands and operators.
 The operations to be performed on the operands are described by the
associated operator.

This expression has 5 operands: A,B,C,D and E and uses 3 operators: *, +, and /.

Four basic operators


 

8
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

Evaluation of Expressions
* and / - have equal precedence
+ and - have equal precedence
 
In evaluating any given expression, operators with a higher precedence are
processed first. When two adjacent operators in an expression have the same
precedence, evaluation is performed from left-to-right.

9
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

Evaluation of Expressions
Any expression within a pair of parentheses will have the highest precedence and
will be evaluated first.

10
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

Evaluation of Expressions

11
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

POSTFIX Notation

12
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

POSTFIX Notation

13
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

POSTFIX Notation

14
CC103 - Data Structure and Algorithm
LESSON 5: Stacks

CLASSWORK
Determine the output of the Postfix algorithm when the following expressions
are used as input.

15
CC103 - Data Structure and Algorithm
LESSON 1: Orientation and Course Introduction

THE END

CC103 - Data Structure and Algorithm

You might also like