0% found this document useful (0 votes)
31 views13 pages

Unit - 2 The Stack

A stack is a linear data structure that follows the Last In First Out (LIFO) principle, where elements are added and removed from the top. Key operations include push, pop, isEmpty, isFull, and display, with applications in string reversal, memory management, and expression evaluation. The document also covers algorithms for push and pop operations, as well as conversion between infix, prefix, and postfix expressions.

Uploaded by

rabinbruhh777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views13 pages

Unit - 2 The Stack

A stack is a linear data structure that follows the Last In First Out (LIFO) principle, where elements are added and removed from the top. Key operations include push, pop, isEmpty, isFull, and display, with applications in string reversal, memory management, and expression evaluation. The document also covers algorithms for push and pop operations, as well as conversion between infix, prefix, and postfix expressions.

Uploaded by

rabinbruhh777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit – 2 The Stack

Definition of stack:-
A stack is a non-primitive linear data structure. It is an ordered collection of item in to
which new item are inserted and form which item may be deleted at one end called the top of
stack unlike the array. As all the deletion and insertion in a stack is done form top of the stack,
the last added element will be the first to be removed from the stack. The definition of stack
provided dynamic (constantly changing object)
• When an item is added to the stacks it is pushed on stack.
• When an item is removed it is pop from stack therefore stack exhibits LIFO( Last In First
Out) or FILO (First In Last Out) properties.

Stack as an ADT:-
Though a very simple technique but is not a flexible way of creation, as the size of stack
has to be declared during program design, after that the size cannot be varied. So it isn’t too
efficient with respect to memory utilization. As the declaration of array is done before the
start of the operation, now if there are too few elements be stored in the stack the statically
allocated memory will be wasted, on the other hand if there are more number of elements to
be stored in the stack then we can’t be able to change the size of array of increase its capacity,
so that it can accommodate new element.
For more details:
https://www.youtube.com/watch?v=ZniDyolzrBw&t=22s

Standard Stack Operations


The following are some common operations implemented on the stack:
• push(): When we insert an element in a stack then the operation is known as a push. If
the stack is full then the overflow condition occurs.

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 1


• pop(): When we delete an element from the stack, the operation is known as a pop. If the
stack is empty means that no element exists in the stack, this state is known as an
underflow state.
• isEmpty(): It determines whether the stack is empty or not.
• isFull(): It determines whether the stack is full or not.'
• peek(): It returns the element at the given position.
• count(): It returns the total number of elements available in a stack.
• change(): It changes the element at the given position.
• display(): It prints all the elements available in the stack.

Operation on stack :-
i) Push (s, x):-
The process of adding a new element to the top of the stack or inserts an element
to stack is called push operation. As new element will be inserted at the top after every
push operation the top is incremented by one. In case the array is full and no new
elements can be accommodated, it is called stack full condition. This condition is called
stack over flow.

Algorithm of push
Push (stack[maxSIZE],item): this algorithm inserts an item at the top of the stack[maxSIZE].
Step 1 : initialize Set
top =-1
Step 2 : repeat steps 3 to 5 until top<maxSIZE-1
Step 3 : read, item
Step 4 : set top=top+1

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 2


Step 5 : set stack [top]=item
Step 6 : print “stack overflow”

Example:-
The function for the stack push operation in c is as follows. Considering stack is declared as
int stack[5], top=-1;
void push()
{
Int item ;
If(top<=4)
{
Printf(”enter the number to be insert:”);
Scanf(“%d”,&item);
Top=top+1;
Stack[top]=item;
}
Else
Printf(”stack overflow”);
}

ii) Pop (s):-

Remove element from stack or the process of deleting an element from the top of stack is
called pop operation. After every pop operation the stack is decremented by one. If there is no
element on the stack and the pop is performed then this will result into stack underflow
condition.

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 3


Algorithm of pop
pop (stack[maxSIZE],item): this algorithm delete an item form the top of the stack.
Step 1 : repeat step 2 to 4 until top≥0
Step 2 : set item= stack[top]
Step 3 : set top=top-1
Step 4 : print, deleted number is ,item
Step 5 : print stack underflow.

Example:-
The function for the stack pop operation in c is as follows.
void pop()
{
Int item ;
If(top>=0)
{
Item=stack[top];
top=top-1;
Printf(”deleted number is: %d”,item);
}
Else
{
printf(”stack is empty”);}

Full Program of Stack (Static Implementation using Array):


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int stack[5];
int top=-1;
void push()
{
int x;
printf("Insert data in stack: \n");
scanf("%d",&x);
if(top==4)
{
printf("Stack OverFlow \n");
}
else
[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 4
{
top=top+1;
stack[top]=x;
}
}
void pop()
{
int item;
if(top==-1)
{
printf("stack is empty \n");
}
else
{
item=stack[top];
top--;
printf("Deleted item is: %d \n", item);
}
}
void display()
{
int i;
for(i=top; i>=0 ; i--)
{
printf("items in stack are: %d\t",stack[i]);
}
}
void main()
{
int ch;
clrscr();
do
{
printf("enter choice no. 1 - Push, 2 - Pop, 3 – Display : \n");
scanf("%d",&ch);
switch(ch)
{
case 1: push();
break;
case 2: pop();
[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 5
break;
case 3: display();
break;
default: printf("Invalid Choice \n");
}
}while(ch!=0);
getch();
}

Stack Applications:
• String reversal: Stack is also used for reversing a string. For example, we want to reverse
a "DataStructure" string, so we can achieve this with the help of a stack.
• UNDO/REDO: It can also be used for performing UNDO/REDO operations. For example,
we have an editor in which we write 'a', then 'b', and then 'c'; therefore, the text written
in an editor is abc. So, there are three states, a, ab, and abc, which are stored in a stack.
There would be two stacks in which one stack shows UNDO state, and the other shows
REDO state.
• Recursion: The recursion means that the function is calling itself again. To maintain the
previous states, the compiler creates a system stack in which all the previous records of
the function are maintained.
• DFS(Depth First Search): This search is implemented on a Graph, and Graph uses the stack
data structure.
• Backtracking: Suppose we have to create a path to solve a maze problem. If we are moving
in a particular path, and we realize that we come on the wrong way. In order to come at
the beginning of the path to create a new path, we have to use the stack data structure.
• Expression conversion: Stack can also be used for expression conversion. This is one of
the most important applications of stack. The list of the expression conversion is given
below:
Infix to prefix
Infix to postfix
Prefix to infix
Prefix to postfix
Postfix to infix
• Memory management: The stack manages the memory. The memory is assigned in the
contiguous memory blocks. The memory is known as stack memory as all the variables
are assigned in a function call stack memory. The memory size assigned to the program is
known to the compiler. When the function is created, all its variables are assigned in the

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 6


stack memory. When the function completed its execution, all the variables assigned in
the stack are released.

Stack application: Evaluation of Infix Postfix and Prefix expression


Evaluation:-
Another application of stack is calculation of postfix expression. To understand what is a
postfix expression let us undergo a discussion. There are basically three types of notation for
an example (mathematical expression is defined as a number operands or data item combined
using several operators).

Type of expression:-
1. Infix expression
2. Prefix expression
3. Postfix expression

Infix expression:-
The infix notation is what we come across in our general mathematics, where the
operator is written in between the operands. For example: the expression to add two numbers
A and B is written in infix notation as: A+B. Note that the operator ‘+’ is written in between the
operands A and B. The reason why this notation is called infix is the place of operator in the
expression.

Prefix expression:-
It is a notation in which the operator is written before the operands, it is also called the
police notation in the honor of the mathematician Jan Lukasiewicz who developed this
notation the same expression when written in prefix notation look likes : +AB , as the operator
‘+’ is written before the operands A and B, this notation is called prefix (pre means before).

Postfix expression:-
In the postfix notation the operators are written after the operands, so it is called the
postfix notation (post means after), it is also known as suffix notation or reverse polish
notation. The above expression if written in postfix expression looks like follows: AB+.

Operator Precedence Order


Priority (high to low) Precedence Order Associativity
1 ( ), { }, [ ] parenthesis
2 ^ exponential operator Right to Left
3 *, / Multiplication/division Left to Right

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 7


4 +,- Addition/subtraction Left to Right

Use of pre and the postfix notation:-


for example: a “C” function program to return sum of the variable ‘A’ and ‘B’ (passed as
argument) is called or invoked by the instruction :- add(int a, int b).
Note that the operator add (name of the function) precedes the operands ‘A’ and ‘B’.
Because the postfix notation is a type of notation which is most suitable for computer to
calculate the expression and is the universally accepted notation for designing ALU and CPU
therefore it is necessary for us to study the postfix notation. Any expression entered into the
computer is first converted into postfix notation and then calculated.

Advantages of using postfix expression:-


In postfix notation operands appears before the operator. This is no need for operators
precedence and after rules. As soon as an operator arrears in the postfix expression the top
most operands are popped off and are calculated applying the encountered operator. Place
the result back onto the stack, doing so the stack will contains finally a single value at the end
of process. The set of rules must be applied to expressions in order to determine the final
value.

Conversion of this infix expression to Prefix Expression and Postfix Expression


Infix Expression: ((a-b)/c)*((d+e)-f)
Prefix Expression: Postfix Expression:
step1: (-ab /c )*(+de -f) step1: (ab- /c) * (de+ -f)
step2: /-abc * -+def step2: ab-c/ * de+f-
step3: */-abc-+def step3: ab-c/de+f-*

Evaluation (calculation) of a Postfix Expression


Algorithm to evaluate a POSTFIX Expression:
This algorithm finds the VALUES of an arithmetic expressions P written in postfix notation. The
following algorithm which uses a STACK to hold operands, evaluates P.
Step 1: Scan the expression from left to right
Step 2: If it is an operand, push it to stack
Step 3: If it is an operator, pull last two operand from stack and perform operation
Step 4: store the output of step 3, back to stack
Step 5: Scan the expression until all operands are consumed
Step 6: Pop the stack and perform operation

Example 1: Calculate of following Postfix Expression


Evaluate:- 623+-382/+*2^3+

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 8


Symbol Operand A Operand B Value(A⊕B) Operand Stack
6 6
2 6, 2
3 6, 2, 3
+ 2 3 2+3 = 5 6,5
- 6 5 6-5 = 1 1
3 1, 3
8 1, 3, 8
2 1, 3, 8, 2
/ 8 2 8/2 = 4 1, 3, 4
+ 3 4 3+4 = 7 1, 7
* 1 7 1*7 = 7 7
2 7, 2
^ 7 2 7^2 49
3 49, 3
+ 49 3 49+3 52

Task1: Calculate following postfix evaluation: 4,5,6,*,+


Task2: Calculate following postfix evaluation: 4 , 5 , + , 7 , 2 , - , *

Example 2:
Evaluate the expression 5 6 2 + * 12 4 / - in tabular form showing stack after every step
Step Input Symbol/Element Stack Output (if
credited)
1 5 Push 5
2 6 Push 5, 6
3 2 Push 5, 6, 2
4 + Pop (2 Element) 5 6+2=8
5 Push Result (8) 5, 8
6 * Pop (2 Element) 5*8=40
7 Push Result (40) 40
8 12 Push 40, 12
9 4 Push 40, 12, 4
10 / Pop (2 Element) 40 12/4=3
11 Push Result(3) 40, 3
12 - Pop (2 Element) 40-3=37
13 Push Result(37) 37
14 No more Elements 37 Results

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 9


Infix to Postfix Conversion:
Rules to convert Infix expression to postfix expression:
1) Print Operands as they arrive
2) If Stack is empty or contains a left parenthesis on top, push the incoming operator onto the
stack
3) If incoming symbol is "(", push it onto stack
4) If incoming symbol is ")" pop the stack & print the operators until left parenthesis is found
5) If incoming symbol has higher precedence than the top of the stack, push it on the stack
6) If incoming symbol has lower precedence than the top of the stack, pop & print the top,
then test the incoming operator against the new top of the stack
7) If incoming operator has equal precedence with the top of the stack, use associativity rule
8) At the end of the expression, pop & print all operators of stack

Note:
I) if associativity L to R then pop & print the top of the stack & then push the incoming
operator
II) If associativity R to L then push the incoming operator

Example – 1: convert following Infix expression to postfix expression:


A-B/C*D+E
Symbol Stack Expression
A A
- - A
B - AB
/ -/ AB
C -/ ABC
* -* ABC/
D -* ABC/D
+ + ABC/D*-
E + ABC/D*-E
Final Expression after conversion into postfix ABC/D*-E+

Example – 2: Convert following infix expression to postfix expression:


A+(B*C-(D/E)*G)*H
Symbol Stack Expression
A A
+ + A
( +( A

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 10


B +( AB
* +(* AB
C +(* ABC
- +(- ABC*
( +(-( ABC*
D +(-( ABC*D
/ +(-(/ ABC*D
E +(-(/ ABC*DE
) +(- ABC*DE/
* +(-* ABC*DE/
G +(-* ABC*DE/G
) + ABC*DE/G*-
* +* ABC*DE/G*-
H +* ABC*DE/G*-H
Final Expression after conversion into postfix ABC*DE/G*-H*+

Task1: convert the following Infix to Postfix Expression:


((A+B)-C*(D/E))+

Task2: convert the following Infix to Postfix Expression:


K + L - M*N + (O^P) * W/U/V * T + Q

Evaluation of Prefix Expression:


Step 1: Scan from Right to Left (or simply reverse the expression)
Step 2: Do follow same rule as Postfix Expression Evaluation
Step 3: After the final Postfix expression again, we have to reverse the value to find prefix
expression

Rules for the conversion of infix to prefix expression:

1. First, reverse the infix expression given in the problem.


2. Scan the expression from left to right.
3. Whenever the operands arrive, print them.
4. If the operator arrives and the stack is found to be empty, then simply push the operator
into the stack.
5. If the incoming operator has higher precedence than the TOP of the stack, push the
incoming operator into the stack.

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 11


6. If the incoming operator has the same precedence with a TOP of the stack, push the
incoming operator into the stack.
7. If the incoming operator has lower precedence than the TOP of the stack, pop, and print
the top of the stack. Test the incoming operator against the top of the stack again and
pop the operator from the stack till it finds the operator of a lower precedence or same
precedence.
8. If the incoming operator has the same precedence with the top of the stack and the
incoming operator is ^, then pop the top of the stack till the condition is true. If the
condition is not true, push the ^ operator.
9. When we reach the end of the expression, pop, and print all the operators from the top
of the stack.
10.If the operator is ')', then push it into the stack.
11.If the operator is '(', then pop all the operators from the stack till it finds ) opening bracket
in the stack.
12.If the top of the stack is ')', push the operator on the stack.
13.At the end, reverse the output.

Example – 3: Convert following infix expression to prefix expression:


a/b-(c+d)-e
Reverse the expression
e-)d+c(-b/a
Symbol Stack Expression
e e
- - e
) -) e
d -) ed
+ -)+ ed
c -)+ edc
( - edc+
- -- edc+
b -- edc+b
/ --/ edc+b
a --/ edc+ba
Final Expression edc+ba/--
Reverse of final expression (in prefix form) --/ab+cde

Example – 4: Convert following infix expression to prefix expression:


K + L - M * N + (O^P) * W/U/V * T + Q

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 12


We need first to reverse the expression
Q+T*V/U/W*)P^O(+N*M–L+K

Symbol Stack Expression


Q Q
+ + Q
T + QT
* +* QT
V +* QTV
/ +*/ QTV
U +*/ QTVU
/ +*// QTVU
W +*// QTVUW
* +*//* QTVUW
) +*//*) QTVUW
P +*//*) QTVUWP
^ +*//*)^ QTVUWP
O +*//*)^ QTVUWPO
( +*//* QTVUWPO^
+ ++ QTVUWPO^*//*
N ++ QTVUWPO^*//*N
* ++* QTVUWPO^*//*N
M ++* QTVUWPO^*//*NM
- ++- QTVUWPO^*//*NM*
L ++- QTVUWPO^*//*NM*L
+ ++-+ QTVUWPO^*//*NM*L
K ++-+ QTVUWPO^*//*NM*LK
Final Expression QTVUWPO^*//*NM*LK+-++
Reverse the final Expression (infix expression) ++-+KL*MN*//*^OPWUVTQ

Prefix to Postfix conversion:


https://www.javatpoint.com/conversion-of-prefix-to-postfix-expression

Postfix to Prefix conversion:


https://www.javatpoint.com/conversion-of-postfix-to-prefix-expression

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 13

You might also like