1
STACK
Last In First Out (LIFO) data structure
Source: https://visualgo.net/en/list?slide=4
2
STACK – contd...
Last In First Out (LIFO) data structure
source: https://data-flair.training/blogs/stack-in-c-cpp /
3
STACK – operations
Stack - linear data structure where insertion &
deletion are done in one end only – called “Top” of
stack
source:http://www.itportal.in/2011/10/stack-operations-explanation-with.html
Animation: http://www.csanimated.com/animation.php?t=Stack
4
STACK – operations – contd...
source :
https://medium.com/swlh/stacks-and-queues-simplified-ef0f838fc53
4
5
STACK – operations –example
Empty Stack
Push 5
S
5
S 4
5 3
4 2
3
1
2
1
0 Top = -1+1
S
=0
0
5
4
Top = -1 3
2
1
5
0 Top = -1+1 6
STACK – operations –example
Push 13
S
5
4
3
2
1
Top = 0+1
5 =1
0
S
5
4
3
2
13 Top = 0+1
1
5 =1
0
7
STACK – operations –example
POP
S
5
4
3
2
13 Top =
1
S[top] = 13 is printed 5 1
0
S
5
4
3
2
13
1
5 Top = 1-1 =
0 0 8
Problem
Push 12, 25, 66, 37, 11 into a stack. Pop 2
times. Push 35& 48. What is the content of
stack?
9
Implementation of Stack
1) Array Implementation of Stack
2) Linked List implementation of Stack
10
Linked List Implementation of Stack
Pointer to dummy header can be used as ‘top’
Stack S
top
100
4
0
1000 2500 4000 3500
11
Linked List Implementation of Stack
Push 10
Stack S
top
100
4
0
1000 2500 4000 3500
temp
10
12
Linked List Implementation of Stack
Pop
Stack S
top
100
4
0
1000 2500 4000 3500
13
Linked List Implementation of Stack
After Pop
Stack S
top
250
4
0
2500 4000 3500
14
Program for linked list Stack
/* Header file – ‘stack.h’
#include <stdio.h>
typedef int elementType ;
struct node
{
elementType data;
struct node *next;
}
typedef struct node *position, stack;
15
Linked list Stack – header file-contd...
/* Function for inserting element*/
void Push(elementType, stack);
/* Function for deleting element */
elementType Pop(stack);
/* Function for Initializing Stack */
stack Initialize();
/* Function for showing top element*/
elementType Peep(stack);
16
Linked list Stack – header file-contd...
/* Function for checking if stack is
empty*/
int IsEmpty(stack);
/* Function for displaying stack*/
void Display (stack);
/* Function for deleting entireStack */
void DeleteStack();
17
Linked list Stack – Implementation file
/* stack.c*/
#include “stack.h”
/* Function for Initializing Stack */
18
Implementation file – INITIALIZE()
/* Function for initializing dummy header*/
position Initialize( )
{
position temp ;
/* Allocate memory space for new node */
/*Check if memory has been allocated
properly */
19
Implementation file – INITIALIZE()– contd...
/* Assign data value to temporary node
*/
/*Assign the pointer to temporary
node */
/* Return the pointer*/
}
20
Implementation file – Push()
/* Function for inserting the node ‘x’ */
void Push(elementType x, stack S)
{
position temp ;
/* Allocate memory space for new node */
/*Check if memory has been allocated
properly */
21
Implementation file – Push() – contd...
/* Assign data value to temporary node */
/*Adjust the pointers for push operation*/
22
Implementation file – Pop()
/*Function for Pop */
elementType Pop(stack S )
{
elementType y;
/* Check for empty stack */
/*Store in temporary variable*/
23
Implementation file – Pop()
/* Adjust pointers */
/* free memory space */
/* return data field*/
24
Implementation file – Peep()
elementType Peep(stack S)
{
/* Check for Empty Stack */
/* return top most element */
25
Implementation file – IsEmpty()
/* Function for checking whether Stack
is Empty*/
int IsEmpty(stack S)
{
return
26
Implementation file – Display()
/* Function for displaying Stack contents*/
int Display (stack S)
{
/* Check for empty stack */
/* start with first node */
/* Looping*/
/* print data*/
/* move to next node*/
}
27
Array Implementation of Stack
Stack
s
size
top
Arra
y
top = 3
55 3
15 2
20 1
40 0
28
Program for Array implementation of Stack
/* Header file – ‘stack.h’ */
#include <stdio.h>
typedef int elementType ;
struct stackRec
{
int capacity;
int top;
elementType *Array;
}
typedef struct stackRec *stack;
29
Program for Array implementation of Stack - contd...
/* Function for inserting element*/
void Push(elementType, stack);
/* Function for deleting element */
elementType Pop(stack);
/* Function for Initializing Stack */
stack Initialize(int);
/* Function for showing top element*/
elementType Peep(stack);
30
Linked list Stack – header file-contd...
/* Function for checking if stack is empty*/
int IsEmpty(stack);
/* Function for checking if stack is full*/
int IsFull(stack);
/* Function for displaying stack*/
void Display (stack);
/* Function for deleting entireStack */
void DeleteStack();
31
Linked list Stack – Implementation file
/* stack.c*/
#include “stack.h”
/* Function for Initializing Stack */
32
Implementation file – INITIALIZE()
/* Function for initializing dummy header*/
stack Initialize(int capacity )
{
/* Allocate memory space for new node */
/*Check if memory has been allocated
properly */
33
Implementation file – INITIALIZE()– contd...
/* Allocate memory for array*/
/*Check if memory has been allocated
properly */
/*Initialze top and size */
/* Return the pointer*/
} 34
Implementation file – Push()
/* Function for inserting the node ‘x’ */
void Push(elementType x, stack S)
{
/* check for full stack */
/*Increment top & store x */
}
35
Implementation file – Pop()
/*Function for Pop */
elementType Pop(stack S )
{
elementType y;
/* Check for empty stack */
/*Store in temporary variable*/
/* Decrement top pointer */
/* Return top element */
} 36
Implementation file – Peep()
elementType Peep(stak S)
{
/* Check for Empty Stack */
/* return top most element */
37
Implementation file – IsEmpty()
/* Function for checking whether Stack
is Empty*/
int IsEmpty(stack S)
{
return
38
Implementation file – IsFull()
/* Function for checking whether Stack
is full*/
int IsFull (stack S)
{
return
39
Implementation file – Display()
/* Function for displaying Stack
contents*/
void Display (stack S)
{
int i;
/* Check for empty stack */
/* Looping*/
/* print data*/
}
40
Implementation file – DeleteStack()
/* Function for deleting Stack */
void DeleteStack (stack S)
{
/* Check if stack is there */
If (S != NULL)
{
/* dispose array*/
/* dispose structure*/
}
41
Applications of Stack
1) Checking whether the given string is
palindrome or not
2) Parentheses Checking
Eg: ([{ a b d }])
1) Empty
stack Ch = ‘(‘ 3) Ch = ‘[‘
2) Push Push
[
( (
42
Parentheses checking
Eg: : ([{ a b d }]) Ch = ‘b‘
6)
Ignore
Ch = ‘{‘ Ch = ‘a‘
4) Push 5) Ignore 7) Ch = ‘c‘
Ignore
{ { Ch = ‘}‘
8) Pop
[ [ 9)
( (
{
[
[
(
(
Popped out character = ‘{‘
Therefore , match
43
Parentheses checking – contd...
Eg: : ([{ a b d }])
12)
Ch = ‘)‘
10) Ch = ‘]‘ 11) Pop 13)
Pop
[ (
(
(
Popped out character = ‘(‘
Therefore , match
Popped out character = ‘[‘
Therefore , match
Atlast, stack is empty.
Therefore all parentheses
match/ 44
Applications of Stack – contd...
3) For Function calls – Activation record is
pushed
4)For recursive functions , activation
record for each recursive call
5) Infix to Postfix Expression Conversion
6) Evaluation of Postfix expression
7) Maintaining Expression tree
45
Different notations for arithmetic expressions
1) Infix notation
2) Prefix notation
3) Postfix notation
Infix notation
Operator is between two operands
Eg: a+b*c
Needs parenthesis
Prefix (or) Polish notation
Opeator is written before two
operands
Eg: +ab
Eg2: *+abc
46
Different notations for arithmetic expressions – contd..
Postfix (or) Reverse Polish notation
Operator is written after two operands
Eg: ab+
Eg2: ab+c*
Compiler uses this notation
Manual Procedure for converting infix
notation to Prefix notation
1) Put parenthesis for each operation
2) Move operator to the position of
nearest left parenthesis
3) Omit all right parentheses
Eg: (a+b)*c
Eg2 : a*b/c+d 47
48
Different notations for arithmetic expressions – contd..
Manual Procedure for converting infix
notation to Postfix notation
1) Put parenthesis for each operation
2) Move operator to the position of
nearest right parenthesis
3) Omit all left parentheses
Eg: (a+b)*c
Eg2 : a*b/c+d
49
Algorithm for converting infix expression to postfix
expression
1) Append # to the infix expression as
delimiter.
2) Repeat steps 3 to 7 until the character is
delimiter #.
3) Read the next charcater ‘ch’.
4) If ‘ch’ is an operand, then directly
append it to ‘postfix’ string.
5) If ‘ch’ is opeartor or left parenthesis,
then
Pop all entries from the stack and append
it to ‘postfix’ until we find a symbol with
lower priority ie. Symbols with greater
than or equal priority are popped out
Assume that priority of ‘(‘ is the highest
and it is not popped until ‘)’ is seen
Then push ‘ch’.
50
Algorithm for converting infix expression to postfix
expression – contd...
6) If ‘ch’ is ‘)’, then
Pop all symbols from stack and
append it to ‘postfix’ string until ‘(‘ is
popped out
Ignore ‘(‘.
7) If ‘ch’ is the delimiter’#’, then
Pop all symbols from stack and
append it to ‘postfix’ string until stack
becomes empty.
8) At last, print ‘postfix’ string.
----------
51
Example for converting infix expression to postfix
expression
Input is
a+(b*c+d)+e
Step 1 :
Append # as delimiter
a+(b*c+d)+e #
Step 2 :
ch = ‘a’
operand. Therefore append it to
‘postfix’ string
a
postfix
52
Example for converting infix expression to postfix
expression – contd...
Step 3 :
ch = ‘+’
Stack is empty
Therefore Push ‘+’ top =
Step 4 : + 0
stac
ch = ‘(’
k
priority(+) < priority( ‘(‘ )
Therefore do not pop .
Push ‘(‘
top =
( 1
+
stac 53
Example for converting infix expression to postfix
Step 5 : expression – contd...
ch = ‘b’
operand
Therefore append it to ‘postfix’
a b
postfix
Step 6 :
ch = ‘*’ top =
priority( ‘(‘) > priority(*) * 2
Therefore do not pop from stack. (
Push * onto stack
+
stac
k 54
Example for converting infix expression to postfix
expression – contd... a+(b*c+d)+e #
Step 7: ch = ‘c’
Operand
Therefore append it to ‘postfix’
a b c
postfix
Step 8: ch = ‘+’
priority(*) > priority(+) top =
Therefore pop & * 2
append it to ‘postfix’ (
( +
+ stac
k
55
Example for converting infix expression to postfix
expression – contd... a+(b*c+d)+e #
Step 8 :
a b c *
postfix
top =
‘(‘ should not be
1
popped out (
Therefore push ‘+’
top = +
stac
+ 2 k
(
+ (
stac +
k
56
Example for converting infix expression to postfix
expression – contd... a+(b*c+d)+e #
Step 9 : Ch = ‘d’
Operand
Therefore append it to ‘postfix’
a b c * d
postfix
top =
Step 10 : Ch = ‘)’
Right parenthesis + 2
Therefore pop all characters upto (
‘(‘ and append it to ‘postfix’
( +
stac
+ k
57
Example for converting infix expression to postfix
expression – contd... a+(b*c+d)+e #
Step 10:
Pop ‘+’
top =
( 1
+
stac
k
a b c * d +
postfix (
+
58
Example for converting infix expression to postfix
expression – contd... a+(b*c+d)+e #
Step 10 :
Pop ‘(’
top =
0
+
stac ‘(‘ is ignored
k
a b c * d +
postfix (
+
59
Example for converting infix expression to postfix
expression – contd... a+(b*c+d)+e #
Step 11: ch = ‘+’
Operator
Therefore pop all characters with
equal and higher priority
ie. Pop ‘+’ and append it to top =
‘postfix’ 0
+
stac
k
top =
stac -1 (
k a b c *+
d + +
postfix
60
Example for converting infix expression to postfix
expression – contd... a+(b*c+d)+e #
Step 11:
Then push ‘ch’ = ‘+’
top =
0
+
stac
k
(
a b c *+
d + +
postfix
61
Example for converting infix expression to postfix
expression – contd... a+(b*c+d)+e #
Step 12:
ch = ‘e’
a b c * d + +
Operand e
postfix
Therefore append it to ‘postfix’
Step 13:
ch = ‘#’
Delimiter top =
0
Therefore pop all characters from +
stac
stack and append it to ‘postfix’
k
a b c * d +( +
+
e +
postfix
62
Example for converting infix expression to postfix
expression – contd... a+(b*c+d)+e #
Step 13:
top =
stac -1
k
Postfix expression is
abc*d++e+
a b c * d +( +
+
e +
postfix
63
Exercise for converting infix expression to postfix
expression
Exercise :
Convert the following infix
expression into postfix
a*(b+c)
(
+
64
Evaluation of postfix expression
Eg:
ab*c- where a=2, b=4, c = 3
Step 1 :
Append delimiter # at the end
ab*c-#
Step 2 : top =
ch = ‘a’ stac -1
operand k
therefore read its value &
push it onto stack
top =
2 0
stac
k
65
Evaluation of postfix expression – contd...
ab*c- where
a=2, b=4, c = 3
Step 3 :
ch = ‘b’
operand
therefore read its value & top =
4 1
push it onto stack
2
Step 4 : stac
ch = ‘*’ k
operator
therefore pop two operands &
apply the operator
2*4=8 top =
Push 8 onto stack 8 0
stac
k
66
Evaluation of postfix expression – contd...
ab*c- where
a=2, b=4, c = 3
Step 5 :
ch = ‘c’
operand
therefore read its value & top =
push it onto stack
3 1
8
Step 6 : stac
ch = ‘-’ k
operator
therefore pop two operands &
apply the operator
8-3=5 top =
Push 5 onto stack 5 0
stac
k
67
Evaluation of postfix expression – contd...
ab*c- where a=2, b=4, c =
3
Step 7 :
ch = ‘#’
top =
delimiter 5 0
therefore pop result stac
from stack k
result = 5
top =
stac -1
k
68
Evaluation of postfix expression
Algorithm:
1) Append # at the end of postfix expression
as delimiter.
2) Repeat steps 3 to 5 until the character ‘ch’
is delimiter #.
3) Read the next character ‘ch’.
4) If ‘ch’ is operand, read its value and push
it onto stack.
69
Evaluation of postfix expression
5) If ‘ch’ is operator,
pop two values from stack
the first popped out value is right
operand
the second popped out value is left
operand
Apply the operator to two operands
and push the result onto stack.
6) If ‘ch’ is #, then pop the result from
stack.
70
Exercise- Evaluation of postfix expression
Evalute the following expression using
stack:
ab*c/d+
where a = 10, b=3, c=2, d = 12
71
Time complexity of stack operations
1. Push operation -
2. Pop operation –
3. Peep opeartion -
72
Lab Exercise- Stack –Odd batch
1. Implement basic operations in Stack
using i) linked list ii) Array
2. Implement i) parenthesis checking ii)
Infix to Postfix conversion using the
object file created in (1).
73
Lab Exercise- Stack – Even batch
1. Implement basic operations in Stack
using i) linked list ii) Array
2. Implement i) postfix expression evaluation
ii) Infix to Postfix conversion using the
object file created in (1).
74