DEFINITION OF STACK
A stack is a linear data structure in which insertions and deletions are
allowed only at the end, called the top of the stack.
/HEAT.
Stack of books Stack of coins
Objects placed inside the glass jars
STACK AS AN ADT
When we define a stack as an ADT (or Abstract Data Type), then we are
only interested in knowing the stack operations from the user point of
view.
Means we are not interested in knowing the implementation details at this
moment. We are only interested in knowing what type ot operations we
can
ertorm on stack.
PRIMARY STACK OPERATIONS
push (data): Inserts data onto stack.
DATA
PR1MAY STACK OPERATIONS
pop(): Deletes the last inserted element from the stack.
DATA
SECONDARY STACK OPERATIONS
top(): returns the last inserted element without removing
it.
SECONDARY STACK OPERATIONS
isEmptyO): returns TRUE if the stack is empty, else returns
FALSE.
isFull(): returns TRUE if the stack is full, else returns FALSE.
yr
List of commands
□
~
push(1)
□ push(2)
□ push(3)
□ pop()
□ isFull)
•
isFull() = FALS E
Array implementation
A stack is a linear data structure in which insertions and deletions are
allowed only at the end, called the top of the stack.
As a stack is a linear data structure, we can implement it using an
array or a
ARRAY IMPLEMENTATION
We know that stack_arr[] is an array and insertion and deletion
operations can be performed at any place but we want the
stack_arr[] to behave like a stack.
Hence, the insertions and deletions must be performed at the end.
For this, we will keep a variable top which will keep track of the
last inserted element or the topmost element in an array.
EMPTY STACK
To indicate that the stack is empty, we will put -l in the variable
top.
PUSH(D)
.
For the push operation:
# top is incremented by I.
# New element is pushed at the position top.
PUSH(1)
For the push operation:
# top is incremented by l.
# New element is pushed at the position top.
SERIES OF PUSH AND POP OPERATIONS
push(2)
push(3)
push(5)
push(10)
push(11)
SERIES OF PUSH AND POP OPERATIONS
1 2 3 5 10 11
push(2)
push(3)
push(S)
push(10)
push(11)
SERIES OF PUSH AND POP OPERATIONS
push(2)
push(3) Not possible. There is not
push(5) enough space in the stack.
push(10) This state is called the
overflow state and the
push(11) new element can't be
push(12) pushed.
SERIES OF PUSH AND POP OPERATIONS
10 11
For the pop operation:
± The element at the position of top is deleted.
# top is decremented by I.
SERIES OF PUSH AND POP OPERATIONS
For the pop operation:
% The element at the position of top is deleted.
k top is decremented by l.
SERIES OF PUSH AND POP OPERATIONS
For the pop operation:
% The element at the position of top is deleted.
# top is decremented by I.
SERIES OF PUSH AND POP OPERATIONS
] } u r
push(2)
push(3)
push(5)
push(10)
push(11)
pop
pop
Question 1 IF the sequence of operations - push (1), push (2), pop, push (1),
push (2), pop, pop, pop, push (2), pop are performed on a stack,
the sequence ot popped out values
(A) 2, 2,1,1, 2 (B) 2, 2, 1,2, 2
(C) 2,1,02, 2,1 (D) 2,1, 2, 2, 2
. ISRO CS 2015
Question 2 Consider the following operations performed on a stack of size 5:
Push(a); Pop(); Push(b); Push(c); Pop(); Push(d); Pop(); Pop(); Push(e)
Which of the following statements is correct?
(A) Underflow occurs (B) Stack operations are performed smoothly
(C) Overflow occurs (D) None of the mentioned
UGC NET CS 92016
July - II
Question 1 Which of the following permutation can be obtained in the same
order u'ng a stack assuming that input is the sequence 5, 6, 7, 8, 9 in that
order?
(A) 7, 8, 9, 5, ( B) 5, 9, 6, 7,8
6 ( D) 9, 8, 7, 5, 6 ISRO CS 92017
(C) 7, 8, 9, 6, 5
Question 2.
Stack A has the entries a, b, c (with a on top). Stack B is
empty. An entry popped out of stack A can be printed immediately or
pushed to stack B. An entry popped out of the stack B can be only be
printed. In this
arrangement, which of the following permutations of a, b, c are not possible?
(A) b, a, c (B) b, c, a
ISRO CS 2018
(C) c, a, b (D) a, b, c
Why linked list representation?
Why should we prefer the beginning of the linked list
as the top of the stack?
Basic idea on how to write a program for linked list
implementation of stack.
\WHY LINKED LIST REPRESENTATION?
Simple Answer • Use linked list when the size of the stack is not
known in advance.
Size is known in
stack 1
advance.
stack No limitation
on the number
of nodes we
can" create:)
TOP OF THE STACK
We will select the beginning of the linked list as the top of the stack.
stack
Let say, we want to insert element 50 onto stack.
This new element will be pushed in front of the linked list.
TOP OF THE STACK
We will select the beginning of the linked list as the top of the stack.
stack
For pop operation, everytime the first node of the linked list will be
deleted. This automatically holds because the top pointer is pointing to the
first node
of the linked list.
Let's try to delete the first node of the linked list.
BUT WHY WE PREFER ADDING AND REMOVING THE FIRST
NODE OF THE LINKED LIST?
Time complexity of adding a node at the end: 0(1)
stack
•
head
tcD
Time complexity of adding a node at the end: 0(1)
stack
head
Time complexity of adding a node at the end:
0(1)
stack
head
Time complexity of adding a node at the end: 0(1)
Time complexity of removing the last node: 0(n)
w
stack 50
head
Deleting the last node of the singly
linked list requires traversal
TIME COMPLEXITY COMPARISON
Inserting a new node Deleting a node
0(1) 0(1)
0(1) At the end O(n)
The code of the function must be similar to the code
of inserting the node at the beginning of the singly linked list.
The code of pop() function must be similar to the code of deleting
the first node of the singly linked list.
Stack overflow occurs when there is no space left to
dynamically allocate the memory. In that case, malloc() function
will return NULL.
tack
.
underflow occurs when top is equal to NU LL.
Stack implementation by using arrays
#include<stdio.h
>
#define size 10
int stack_array[size];
int top=-1;
void push(int ele);
int pop();
void
stack_print();
void
stack_top0;
void
is_empty();
void is_full0;
void stack_freespace();
int main()
{
while(l)
{
int ch,ele,x;
printf("\nl .push\n2.pop\n3 .top\n4.is_empty\n5
.is_full\n6.freespace\n7 .print stack elements");
printf("\n enter your choice");
scanf("%d" &ch);
switch(ch)
{
case 1 :printf("enter the element");
scanf("¾d" ,&ele);
push(ele);
break;
case
2:x=pop();
printf("\n the deleted element is:%d" ,x);
break;
case 3: stack_top();
break;
case 4:is_empty();
break;
case 5
:is_full();
break;
case 6: stack_free space();
break;
case 7: stack_print();
break;
}
return 0;
}
void stack_freespace()
{
float per;
per=((size-I )-top)* 100/size;
printf("stack free percentage is %f'',per);
}
void is_full()
{
if(top==size-1)
printf("stack is overflow");
else
printf("stack is not full");
}
void is_empty()
{
if(top==- I)
{
printf("stack is underflow");
}
else
{
printf("stack is not empty");
}
}
void stack_top()
{
printf("the top of the stack element is %d" ,stack_array[top]);
}
void stack_print()
{
inti;
if(top==- I)
{
printf("stack is empty");
}
else
{
printf("the stack elements are:");
for(i=top;i>=O;i--)
{
printfU"%d\t",stack_array[i]);
}
}
}
void push(int ele)
{
if(size- I ==top)
{
printf("\n stack is overflow");
}
else
{
top=top+ 1;
stack_array[top]=ele;
}
}
int pop()
{
int value;
if(top==- I)
{
printf(" stack underflow");
}
else
{
value=stack_array[top];
top=top-1;
}
return value;
}
Stack implementation by using linked list
#include<stdio.h>
#include<stdlib.h>
struct node
int data;
struct node *link;
} *stack_head;
typedef struct node node;
void print();
void push(int ele);
int main()
int ch,ele;
while(l)
printf("\nl .push\n2.pop\n3 .top\n");
printf("\n enter your choice");
scanf("¾d" ,&ch);
switch(ch)
case 1 :printf("\n enter the element");
scanf("¾d" ,&ele);
push(ele);
break;
case 2:print();
break;
case 3 :pop();
break;
return O;
}
void print()
if(stack_head==NULL)
printf("\n stack is empty");
else
node temp=stack_head;
printf("stack elements from bottom to top is:");
while(temp!=NULL)
printfU"%d\t",temp->data);
temp=temp->link;
}
void push(int ele)
if(stack_head==NULL)
stack_head=(node*)malloc(sizeof(node));
if(stack_head== NULL)
printf("stack over flow");
stack_head->data=ele;
stack_head->link=NULL;
else
node *top=(node*)malloc(sizeof(node));
if(top==NULL)
printf("stack overflow");
exit(O);
top->data=ele;
top->link=stack_head;
stack_head=top;
}}
void pop()
if(stack_head==NULL)
printf("stack under flow");
exit(O);
else
node temp=stack_head;
printf("\n the deleted element is %d",temp->data);
temp=temp->link;
stack_head=temp;
}
Stack applications
1. Evolution of arithmetic expression
2. Conversion from infix to postfix
3. Evolution of postfix expression
4. Recursion
5. Functional calls
6. Back button implementation
7. Undo operation in MS-Word
Comparison;
]
Addition
] f•
first 10 + 4 5 = 70
A
fY uiipMICC1 o
4 ] 4
n £.11rSl, 10 + 4 5 =
PRECEDENCE OF OPERATORS
Priorities of the operators are predefined.
We will consider the five different operators: +, -, , /,
Priority
(Exponentiation) 1 (Highest)
-.-··
(Multiplication) and /
(Division]
+ (Addition) and - (Subtraction) 3 (lowest)
Operators Priority
n (Exponentiatian) 1 (Highest)
• (Multiplication) and J (Division) 2
4 (Addition) and (Subtraction) 3 (Lowest)
A 1 £
I1!1!l 10 + 4 5 = 70
hrsl
Maltiolication
10 +4{5=
Find the result of the following infix expression:
3 +5 7 - 42
-ii
Operators Priority
(Exponentiation 1 (Highest)
)
(Multiplication) and / (Division)
+ (Addition) and - (Subtraction) 3 (Lowest)
Example-3
3 +56-7
254 + 10 - 9
365 k
52 k 7 + 10 I 10
3 + 5 * (7 4) AN
2
8 k
(5 i\
4 + 2) - 6 A
2 I (9 k
3)
Two ways to represent an expression:
Infix Notation
WHAT IS AN INFIX EXPRESSION?
Infix Notation: A + B
The operators are written in between there operands.
sample
L I - ' - • -
A+B/C
.
The expression literally
means
first add A and B, then divide the result by C
MOE INFORMATION
nfix expression requires extra information to make the order ot
evaluation of operators clear.
lt requires the information about precedence and associativity of operators.
Earnele
A+B/C
The usual rule says that the division must be performed before
addition and subtraction.
A +B/C'D-E/(F+G)
A AB/CD-E/(F+G)
A+B/CD-E/(F+G),
The above expression requires multiple scans and every time we have to
reach a different place in an expression for evaluation,
A+B/C'DE/(F+G)
lr
Scan #]. Found an expression between parentheses
(F+G) has the highest priority.
Scan #2. B/C has the second highest priority.
Scan #3. The result of B/C and D must be multiplied next.
INFIX NOTATION REQUIRES MULTIPLE SCANS AND
1IS, THEREFORE, INEFFICIENT (IN TERMS OF TIME
CONSUMPTION)
Two ways to represent an expression:
Post f ix Notation
..
\WHAT IS A POSTFIX NOTAT10N?
Notation: AB +
The operators are written after their operands
ABC/ +
l
The order of evaluation ot operators is left to right with no brackets in the
expression to change the order
ln the example, division comes before addition, and therefore, the
division
must be performed before addition
Infix Expression
Step-1
A+ B / C * D - E / (FG+)
Step-2
A + BC/ D - E / (FG+)
Step-3
A +[BC/ D - E / (FG+)
• I
Operand 2
A + BC/D - E / (FG+)
Step-4
Step-5
ABC/D*+ - EFG+/
Step-6
Postfix Expression
ABC/D+EFG+/•
.
• I
I
.
. i
•
. . i-i
A+B/CD-E/(F+G) ABC/D+EFG+/•
POSTFIX NOTATION DOESN'T REQUIRE MULTIPLE
SCANS (A SINGLE SCAN IS REQUIRED) AND IS,
THEREFORE, EFFICIENT (IN TERMS OF TIME
CONSUMPTION)
ALGORITHM
h
can the syntals cf the expression from left to right and for each symbul,
do the following:
a. If symbol is an operand
Print that symbol onto the screen
b. I+ symbol is a left parenthesis
a Push it an the stack,
c. If symbol is a right parenthesis
m Popi all the oneratnr Frum the stark uintn the first left
parenthesis and print them on the screen_.
a Discard the left and right
parentheses, d. If symbol is an operator
TF the prwcdrnc n" the operators in the stack arr greater than tr
equal to the current uperalur, then
Pop the operators out of the stack and print them onto
the screen, and push the current nprratar onto the stack,
Push the current operator unto the stack.
7+53/51+(3-2)
l
Output: 7
output: 7535
7+53/51+(3-2)
Output:
7+53/51+(3-2)
Output: 75351/+32-¢ %
Example2:
Evolution of postfix Expression
Begin
for each character ch in the postfix expression, do
if ch is an operator 0 , then
a := pop first element from stack
b := pop second element from the stack
res:= b 0 a
push res into the stack
else if ch is an operand, then
add ch into the stack
done
return element of stack top
End
Example:
Let the given expression be "2 31+ 9-". We scan all elements one by one.
1) Scan '2', it's a number, so push it to stack. Stack contains '2'
2) Scan '3', again a number, push it to stack, stack now contains '2 3'
(from bottom to top)
3) Scan '1, again a number, push it to stack, stack now contains '2 31
4) Scan '*', it's an operator, pop two operands from stack, apply the operator
on operands, we get 3*1 which results in 3. We push the result '3' to stack.
The stack now becomes '2 3'.
5) Scan '+', it's an operator, pop two operands from stack, apply the +
operator on operands, we get 3 + 2 which results in 5. We push the result '5'
to stack. The stack now becomes '5'.
6) Scan '9', it's a number, we push it to the stack. The stack now becomes '5
9'.
7) Scan '-', it's an operator, pop two operands from stack, apply the --
operator on operands, we get 5 - 9 which results in -4. We push the result '-4'
to the stack. The stack now becomes '-4'.
8) There are no more elements to scan, we return the top element from
the stack (which is the only element left in a stack).