You are on page 1of 53

Data Structure and Algorithms

Stack

Puneet Kumar Jain

CSE Department
National Institute of Technology Rourkela
Reference
 Most of the content of this presentation belongs to the following
book:

Reema Thareja, “Data structures using C”, 2nd edition, Oxford


University Press, 2014

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Content
 Stack introduction
 Stack representation using array and linked-list
 Operations on stack,
 Applications of stacks
 Reversing a list
 Parentheses checker
 Conversion of an infix expression into a postfix expression
 Evaluation of a postfix expression
 Recursion
 Tower of Hanoi

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Stack
 A stack is a linear data structure
 The elements in a stack are added and removed only from one
end, which is called the TOP.
 Also called a last-in–first-out (LIFO): as the element that was
inserted last is the first one to be taken out.

 Graphically, we may view these operations as follows:

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Operations on stacks
 Createstack(s)—to create s as an empty stack

 Push(s,i)--to push element i onto stack s.

 Pop(s)—to access and remove the top element of the stack s

 Peek(s)—to access the top element of the stacks without


removing it from the stack s.

 Isfull(s)—to check whether the stack s is full

 isempty—to check whether the stack s is empty

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Implementation

 Stacks can be implemented using either arrays or linked lists.

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


ARRAY REPRESENTATION OF STACKS
 In the computer’s memory, stacks can be represented as a linear
array
 TOP: store the address of the topmost element of the stack. It is
this position where the element will be added to or deleted from.
 MAX: store the maximum number of elements that the stack can
hold.
 If TOP = NULL, then it indicates that the stack is empty
 if TOP = MAX–1, then the stack is full.

MAX=10

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Push Operation
 Push operation: insert an element into the stack.
 The new element is added at the topmost position of the stack.
 OVERFLOW:
 TOP=MAX–1, the stack is full
 and no more insertions can be done.

PUSH 6

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Pop Operation
 Pop operation: delete the topmost element from the stack.
 UNDERFLOW
 TOP==NULL: the stack is empty and
 no more deletions can be done.

POP

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Peek Operation
 Peek: returns the value of the topmost element of the stack
without deleting it from the stack.
 TOP == NULL: Stack is empty
 else the value is returned.

PEAK

Returns 5

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Linked list representation
 if the array size cannot be determined in advance, then the other
alternative, i.e., linked representation, is used.
 The storage requirement of linked representation of the stack
with n elements is O(n), and the typical time requirement for the
operations is O(1).
 The START pointer of the linked list is used as TOP. All insertions
and deletions are done at the node pointed by TOP
 Push Operation: insert the new node at the beginning of the linked
stack and name this new node as TOP
 POP Operation: delete the node pointed by TOP, and make TOP point
to the second element of the linked stack
 Peak operation: Returns the data of the node pointed by TOP

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Complexity
 IsEmpty() => check whether top >= 0
 O(1) time
 IsFull() => check whether top == capacity – 1
 O(1) time
 Top() => If not empty return stack[top]
 O(1) time
 Push(theElement) => if full then error message or add at
stack[top+1]
 O(1) time
 Pop() => if not empty, delete from stack[top]
 O(1) time

 Space complexity: O(1)


NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Complexity
 Access (kth element): O(n)

 Search: O(n)

 Insertion: O(1)

 Deletion: O(1)

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


APPLICATIONS OF STACKS
 Reversing a list
 Parentheses checker
 Conversion of an infix expression into a postfix expression
 Evaluation of a postfix expression
 Conversion of an infix expression into a prefix expression
 Evaluation of a prefix expression
 Recursion
 Tower of Hanoi

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Reversing a List
 A list of numbers can be reversed by reading each number from
an array starting from the first index and pushing it on a stack.
 Once all the numbers have been read, the numbers can be
popped one at a time and then stored in the array starting from
the first index.

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Implementing Parentheses Checker
 Stacks can be used to check the validity of parentheses in any
algebraic expression.
 For example, an algebraic expression is valid if for every open
bracket there is a corresponding closing bracket.
Input: exp = “[()]{}{[()()]()}”
Algorithm: Output: Balanced
Declare a character stack S. Input: exp = “[(])”
Output: Not Balanced
Now traverse the expression string exp.
If the current character is a starting bracket ‘(‘ or ‘{‘ or ‘[‘ then push
it to stack.
If the current character is a closing bracket ‘)’ or ‘}’ or ‘]’ 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”
Time Complexity: O(n) Auxiliary Space: O(n) for stack.
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Examples of valid inputs
Valid Input invalid Input

() [(( )

( { } [ ]) ( { } [ ]))

({[][]}) (( { [ ] [ ] } )

[ { { { } ( )} [ ] } [ ] ( ) { } ([ { { { } ( )} [ ] } }[ ] ( ) { } ]
]

Inside parenthesis there can be any valid arithmetic expression.

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Evaluation of Arithmetic Expressions
 Polish Notations: Infix, postfix, and prefix notations are three
different but equivalent notations of writing algebraic
expressions.
Precedence associatively
() L-R
^ R-L
/* L-R
+- L-R

Postfix examples: Prefix examples:


(a) (A–B) * (C+D) (a) (A–B) * (C+D)
[AB–] * [CD+] [–AB] * [+CD]
AB–CD+* *–AB+CD
(b) (A + B) / (C + D) – (D * E) (b) (A + B) / ( C + D) – ( D * E)
[AB+] / [CD+] – [DE*] [+AB] / [+CD] – [*DE]
[AB+CD+/] – [DE*] [/+AB+CD] – [*DE]
AB+CD+/DE*– –/+AB+CD*DE

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Why postfix /prefix notation
 Pre-/postfix notation is easier to parse for a machine.
 Parenthesis are not required
 There is no operator precedence. Just we need to evaluate from
left to write (Postfix), and from right to left (Prefix).
 In case of infix expression, the time required for evaluation is
O(n^2) worst case
 First we traverse the entire expression and find the operator having
highest precedence evaluate it and again follow the same
procedure, till we complete evaluate the expression
 Example: (g+(f+(e+(d+(c+(a+b*z))))))
 But this is not so in case of postfix or infix expression. the time
required for evaluation of postfix expression is O(n)
 Infix to postfix conversion = O(n) + Postfix evaluation = O(n)
 Total time = O(n) + O(n)= O(n)
Ref: https://stackoverflow.com/questions/7562477/why-do-we-need-prefix-postfix-notation
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Conversion of an Infix Expression into a Postfix Expression
 Let I be an algebraic expression written in infix notation. I may contain
parentheses, operands, and operators

Step 1: Add “)” to the end of the infix expression


Step 2: Push “(“ on to the stack
Step 3: Repeat until each character in the infix notation is scanned
“(“ : push it on the stack
“)”: Repeatedly POP from stack and add it to the postfix exp until a “(“ is
encountered and remove the “(“ from stack and do not add it to the postfix
expression
Operand: add it to the postfix expression.
Operator:
a. Repeatedly pop from stack and add each operator to the postfix
expression which has the same precedence or a higher precedence than
b. Push the operator to the stack
Step 4: Repeatedly pop from the stack and add it to the postfix expression until
the stack is empty
Step 5: EXIT
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Example:K+L-M*N+(O^P)*W/U/V*T+Q
 Input exp Stack Postfix Exp Remarks
K K insert operand directly
+ + K push if no operator with high precedence on TOP
L + KL
- - KL+ Associativity L-R, so POP + and add to Postfix
M - KL+M
* -* KL+M operator with low precedence at TOP, so PUSH *
N -* KL+MN
+ + KL+MN*- operator with high precedence at TOP, so POP *-
( +( KL+MN*- just PUSH (
O +( KL+MN*-O
^ +(^ KL+MN*-O no need to check precedence with (
P +(^ KL+MN*-OP
) + KL+MN*-OP^ POP all operators till the opening bracket
* +* KL+MN*-OP^ operator with low precedence at TOP, so PUSH *
W +* KL+MN*-OP^W
/ +/ KL+MN*-OP^W*
U +/ KL+MN*-OP^W*U
/ +/ KL+MN*-OP^W*U/
V +/ KL+MN*-OP^W*U/V
* +* KL+MN*-OP^W*U/V/
T +* KL+MN*-OP^W*U/V/T
+ + KL+MN*-OP^W*U/V/T*+
Q + KL+MN*-OP^W*U/V/T*+Q
KL+MN*-OP^W*U/V/T*+Q+
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Evaluate the following reverse-Polish expression using a
stack:
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Reverse-Polish Notation
Push 1 onto the stack
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Push 1 onto the stack
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

2
1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Push 3 onto the stack
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

3
2
1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Pop 3 and 2 and push 2 + 3 = 5
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

5
1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Push 4 onto the stack
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

4
5
1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Push 5 onto the stack
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

5
4
5
1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Push 6 onto the stack
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

6
5
4
5
1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Pop 6 and 5 and push 5 × 6 = 30
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

30
4
5
1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Pop 30 and 4 and push 4 – 30 = –26
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

–26
5
1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Push 7 onto the stack
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

7
–26
5
1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Pop 7 and –26 and push –26 × 7 = –182
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

–182
5
1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Pop –182 and 5 and push –182 + 5 = –177
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

–177
1
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Pop –177 and 1 and push 1 – (–177) = 178
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

178
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Push 8 onto the stack
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

8
178
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Push 1 onto the stack
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

9
8
178
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Pop 9 and 8 and push 8 × 9 = 72
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

72
178
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Pop 72 and 178 and push 178 + 72 = 250
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +

250
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Reverse-Polish Notation
Thus
1 2 3 + 4 5 6 × – 7 × + – 8 9 × +
evaluates to the value on the top: 250
The equivalent in-fix notation is
((1 – ((2 + 3) + ((4 – (5 × 6)) × 7))) + (8 × 9))

Incidentally,
1 – 2 + 3 + 4 – 5 × 6 × 7 + 8 × 9 = – 132
which has the reverse-Polish notation of
1 2 – 3 + 4 + 5 6×7× – 8 9 × +

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Evaluation of postfix notation

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Function calls
 Consider an example, where we are executing function A. In the
course of its execution, function A calls another function B.
Function B in turn calls another function C, which calls function D.
 In order to keep track of the returning point of each active
function, a special stack called system stack or call stack is used.
 Whenever a function calls another function, the calling function is
pushed onto the top of the stack.
 This is because after the called function gets executed, the control
is passed back to the calling function.

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Recursion
 Recursive function: a function that calls itself to solve a smaller version of its
task until a final call is made which does not require a call to itself.
 Since a recursive function repeatedly calls itself, it makes use of the system
stack to temporarily store the return address and local variables of the calling
function.
 Every recursive solution has two major cases.
 Base case: the problem is simple enough to be solved directly without making
any further recursive calls.
 Recursive case: the problem at hand is divided into simpler sub-parts. The
result is obtained by combining the solutions of simpler sub-parts.

 Example:
int Fact(int n)
{
if(n==1) //Base case
return 1;
Else // Recursive case
return (n * Fact(n–1));
}

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Tower of Hanoi
 It says, ‘if you can solve n–1 cases, then you can easily solve the nth case’.
 Rules:
 Only one disk can be moved at a time.
 disk can only be moved if it is the uppermost disk on a stack.
 No disk may be placed on top of a smaller disk
 Algorithm:
 Step 1 − Move n-1 disks from source to aux
 Step 2 − Move nth disk from source to dest
 Step 3 − Move n-1 disks from aux to dest

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Recursive Solution

A B C
• n > 0 gold disks to be moved from A to C using B
• move top n-1 disks from A to B using C
Recursive Solution

A B C
• move top disk from A to C
Recursive Solution

A B C
• move top n-1 disks from B to C using A
Recursive Solution

A B C
• moves(n) = 0 when n = 0
• moves(n) = 2*moves(n-1) + 1 = 2n-1 when n > 0
• End of chapter

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Types of Recursion
 Direct Recursion:
 A function is said to be directly recursive if it
explicitly calls itself.

 Indirect Recursion
 A function is said to be indirectly recursive if it
contains a call to another function which
ultimately calls it.

 Tail Recursion
 A recursive function is said to be tail recursive
if no operations are pending to be performed
when the recursive function returns to its
caller. when the called function returns, the
returned value is immediately returned from
the calling function. Tail recursive functions are
highly desirable because they are much more
efficient to use as the amount of information
that has to be stored on the system stack is
independent of the number of recursive calls.
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Non-Tail recursion to tail recusrion
 Converting Recursive Functions to Tail Recursive

 A non-tail recursive function can be converted into a tail-recursive


function by using an auxiliary parameter as we did in case of the
Factorial function.
 The auxiliary parameter is used to form the result.
 When we use such a parameter, the pending operation is incorporated
into the auxiliary parameter so that the recursive call no longer has a
pending operation
 We generally use an auxiliary function while using the auxiliary
parameter to keep the syntax clean
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”
Linear vs Non-linear recursion
 linearly recursive: when the pending operation (if any) does not
make another recursive call to the function.
 For example, The factorial function is linearly recursive as the
pending operation involves only multiplication to be performed and
does not involve another recursive call to Fact.

 Tree recursive (or non-linearly recursive): if the pending


operation makes another recursive call to the function.
 For example, the Fibonacci function in which the pending operations
recursively call the Fibonacci function.

NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”


Advantage and drawbacks of recursion
 The advantages of using a recursive program include the following:
 Often tend to be shorter and simpler than non-recursive ones.
 Code is clearer and easier to use.
 Recursion works similar to the original formula to solve a problem.
 Recursion follows a divide and conquer technique to solve problems.
 In some (limited) instances, recursion may be more efficient.

 The drawbacks/disadvantages include the following:


 Recursion is (sometimes) difficult to design concept.
 Recursion is implemented using system stack. If the stack space on the system
is limited, recursion to a deeper level will be difficult to implement.
 Aborting a recursive program in midstream can be a very slow process.
 Takes more memory and time to execute as compared to nonrecursive version.
 It is difficult to find bugs, particularly while using global variables.
 The advantages of recursion pay off for the extra overhead involved in terms of
time and space required.
NIT Rourkela Puneet Kumar Jain “Data Structure and Algorithms”

You might also like