0% found this document useful (0 votes)
0 views

DS_Modul 2 (1)

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. It is commonly used in function calls, memory management, and can be implemented using arrays or linked lists. The document also discusses operations such as push, pop, peek, and the evaluation of arithmetic expressions using infix, prefix, and postfix notations.

Uploaded by

rashmipathak2006
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

DS_Modul 2 (1)

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. It is commonly used in function calls, memory management, and can be implemented using arrays or linked lists. The document also discusses operations such as push, pop, peek, and the evaluation of arithmetic expressions using infix, prefix, and postfix notations.

Uploaded by

rashmipathak2006
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 92

Stacks

Stack is a linear data structure which stores its elements in an ordered


manner
• 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.

• A stack is called a LIFO (Last-In-First-Out) data structure, as the


element that was inserted last is the first one to be taken out

Stack is an abstract data type used in many languages

Stack can be either fixed size or can be varied ie dynamic resizing .


where do we need stacks in computer
science ?
Ans: function calls

Example:
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.

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
Now when function E is executed, function D will be removed from the top of the
stack and executed. Once function D gets completely executed, function C will be
removed from the stack for execution. The whole procedure will be repeated until all
the functions get executed.
Position Of stack
Position of top Status of Stack
-1 Stack is empty
0 Only one element in stack
N-1 Stack is full
N Overflow of stack
Stacks can be implemented using either arrays or linked lists

• In the computer’s memory, stacks can be represented as a linear array.

• Every stack has a variable called TOP associated with it, which is used to store the address of
the topmost element of the stack.

• It is this position where the element will be added to or deleted from. There is another variable called
MAX, which is used to store the maximum number of elements that the stack can hold.
Stack_arr[]

In an array insertion and deletion can be done in any place

Stack_arr[] is an array implementation of stack so it can perform insertion/deletion at the end only
1. Push Operation
•The push operation is used to insert an element into the stack.

•The new element is added at the topmost position of the stack.

•Before inserting the value, first check if TOP=MAX–1, because if


that is the case, then the stack is full and no more insertions can be
done.

•If an attempt is made to insert a value in a stack that is already


full, an OVERFLOW message is printed
For push operation top has to be incremented by 1
Then value can be inserted on that top.
Pop Operation

•The pop operation is used to delete the topmost element from the stack.

•However, before deleting the value, first check if TOP=NULL because if that is
the case, then it means the stack is empty and no more deletions can be done.

• If an attempt is made to delete a value from a stack that is already empty, an


UNDERFLOW message is printed
Peek Operation

•Peek is an operation that returns the value of the topmost


element of the stack without deleting it from the stack

•Peek operation first checks if the stack is empty, i.e., if TOP = NULL,
then an appropriate message is printed, else the value is returned
Secondary Operators
• Size() : return to the size or number of elements in the stack
• isEmpty(): return true if the stack is empty else return false
• isFull() : return true if the stack is full else return false
Write a program to perform Push,
Pop and operations on a stack
#include <stdio.h>
Preprocessor directive
#define LIM 10
void push();
void pop();
void peek();
void display();
int choice,num,top=-1;
int stack[LIM];
int space=0;
int main()
{
do
{
printf("____MENU____\n");
printf("1. TO INSERT AN ELEMENT\n");
printf("2. TO DELETE AN ELEMENT\n");
printf("3. TO DISPLAY TOPMOST
ELEMENT\n");
printf("4. TO DISPLAY ALL ELEMENTS\n");
printf("5. TO EXIT THE PROGRAM\n");
printf("_____________\n");
printf("ENTER YOUR OPTION:\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
push();
printf("\n");
break;
case 2:
pop();
printf("\n");
break;
case 3:
peek();
printf("\n");
break;
case 4:
display();
printf("\n");
break;
case 5:
break;
default:
printf("CHOICE IS INVALID\n");
}
}while(choice!=5);
return 0;
}
void push()
{
printf("ENTER THE NUMBER TO BE INSERTED: ");
scanf("%d",&num);
if(top==LIM-1)
{
printf("STACK IS FULL\n");
}
else
{
top++;
stack[top]=num;
}
}
void pop()
{
if(top==-1)
{
printf("STACK IS EMPTY\n");
}
else
{
space=stack[top];
printf("THE ELEMENT DELETED IS: %d ",stack[top]);
top--;
printf("\n");
}
}
void peek()
{
if(top==-1)
{
printf("STACK IS EMPTY\n");
}
else
{
printf("THE ELEMENT AT THE TOP IS: %d\n",stack[top]);
}
}
void display()
{
if(top==-1)
{
printf("NO ELEMENTS IN THE STACK\n");
}
else
{
int i;
printf("THE ELEMENTS IN THE STACK ARE:\n");
for(i=top;i>=0;i--)
{
printf("%d\t",stack[i]);
}
printf("\n");
}
}
Write a program to implement a stack using array and hold top always in 0 th location

Last inserted elements always place in the zero th place

Eg:
3 5 6 7 8
1st element
0th
top

Keep track of first inserted element


Shift all elements one step towards right and push the new element at index 0
#include <stdio.h>
#define max 5
int stack_arr[max];
int zero =-1;

void push();
void display();
Instead of writing push() n times to read ‘n’ data we can use for loop inside the push function
MULTIPLE STACKS
•While implementing a stack using an array, the size of the array must be known in
advance.

•If the stack is allocated less space, then frequent OVERFLOW conditions will be
encountered.

•To deal with this problem, the code will have to be modified to reallocate more
space for the array.

•In case allocate a large amount of space for the stack, it may result in sheer
wastage of memory.

•Thus, there lies a trade-off between the frequency of overflows and the space
allocated. So, a better solution to deal with this problem is to have multiple stacks or
to have more than one stack in the same array of sufficient size
Array STACK[n] is used to represent two stacks, Stack A and Stack B.

The value of n is such that the combined size of both the stacks will never exceed n
While operating on these stacks, it is important to note one thing—

Stack A will grow from left to right, whereas

Stack B will grow from right to left at the same time.


Write a program to implement multiple stacks
#include <stdio.h>

#include <conio.h>

#define MAX 10

int stack[MAX],topA=–

1,topB=MAX;
void pushA(int val)
{
if(topA==topB–1)
printf("\n OVERFLOW");
else
{
topA+= 1;
stack[topA] = val;
}
}
int popA()
{
int val;
if(topA==–1)
{
printf("\n UNDERFLOW");
val = –999;
}
else
{
val = stack[topA];
topA––;
}
return val;
}
void display_stackA()
{
int i;
if(topA==–1)
printf("\n Stack A is
Empty");
else
{
for(i=topA;i>=0;i––)
printf("\t %d",stack[i]);
}
}
void pushB(int val)
{
if(topB–1==topA)
printf("\n OVERFLOW");
Else
{
topB –= 1;
stack[topB] = val;
}
}
int popB()
{
int val;
if(topB==MAX)
{
printf("\n UNDERFLOW");
val = –999;
}
else
{
val = stack[topB];
topB++;
}
}
void display_stackB()
{
int i;
if(topB==MAX)
printf("\n Stack B is
Empty");
else
{
for(i=topB;i<MAX;i++)
printf("\t %d",stack[i]);
}
}
void main()
{
int option, val;
clrscr();
do
{
printf("\n *****MENU*****");
printf("\n 1. PUSH IN STACK A");
printf("\n 2. PUSH IN STACK B");
printf("\n 3. POP FROM STACK
A");
printf("\n 4. POP FROM STACK
B");
printf("\n 5. DISPLAY STACK A");
printf("\n 6. DISPLAY STACK B");
printf("\n 7. EXIT");
printf("\n Enter your choice");
switch(option)
{
case 1: printf("\n Enter the value to
push on Stack A : ");
scanf("%d",&val);
pushA(val);
break;
case 2: printf("\n Enter the value to
push on Stack B : ");
scanf("%d",&val);
pushB(val);
break;
case 3: val=popA();
if(val!=–999)
printf("\n The value popped from Stack
A = %d",val);
break;
case 4: val=popB();
if(val!=–999)
printf("\n The value popped from
Stack B = %d",val);
break;
case 5: printf("\n The contents
of Stack A are : \n");
display_stackA();
break;
case 6: printf("\n The contents
of Stack B are : \n");
display_stackB();
break;
}
}while(option!=7);
getch();
}
Evaluation of Arithmetic Expressions
There are mainly three methods to represent an algebraic expression

• Infix

• Postfix

• prefix
Infix notation

The operator is placed in between the operands.

For example, A+B; here, plus operator is placed between the two operands
A and B.

computers find it difficult to parse as the computer needs a lot of information to


evaluate the expression. Information is needed about operator precedence and
associativity rules, and brackets which override these rules. So, computers work
more efficiently with expressions written using prefix and postfix notations
Prefix notation (Polish notation) Postfix notation (Reverse Polish
notation)

To develop a parenthesis-free prefix notation and a postfix notation

In postfix notation, the operator is placed after the operands.


For example,
if an expression is written as A+B in infix notation, the same expression can be written as AB+ in
postfix notation.
The order of evaluation of a postfix expression is always from left to right. Even brackets cannot alter
the order of evaluation.
•A postfix operation does not even follow the rules of operator precedence.
•The operator which occurs first in the expression is operated first on the operands.
For example, given a postfix notation AB+C*. While evaluation, addition will be performed
prior to multiplication.
• In a postfix notation, operators are applied to the operands that are immediately left to them.
example, AB+C*, + is applied on A and B, then * is applied on the result of addition and C.

prefix notation is evaluated from left to right


•The only difference between a postfix notation and a prefix notation is that in a prefix notation, the
operator is placed before the operands.
For example, if A+B is an expression in infix notation, then the corresponding expression in
prefix notation is given by +AB.

•While evaluating a prefix expression, the operators are applied to the operands that are present
immediately on the right of the operator.

•prefix expressions do not follow the rules of operator precedence and associativity, and even brackets
cannot alter the order of evaluation
End of Module 2
Modul 6: Applications of Data Structures
Stacks: Conversion of Arithmetic Expressions using Infix,
Prefix and Postfix Notations, Parentheses Checker.
Conversion of Arithmetic Expression

Convert the following infix expressions into postfix expressions

Infix Expression (A–B) * (C+D)

[AB–] * [CD+]

AB–CD+*
Infix Expression

(A + B) / (C + D) – (D * E)
Infix Expression (A + B) / (C + D) – (D * E)

[AB+] / [CD+] – [DE*]

[AB+CD+/] – [DE*]

Post fix expression AB+CD+/DE*–


A postfix operation does not even follow the rules of operator precedence.

The operator which occurs first in the expression is operated first on the
operands.

Example
given a postfix notation AB+C*.
While evaluation, addition will be performed prior to multiplication.
Evaluation of post fix expression

Expression will be scanned left to right , as soon as an operator encounter directly


apply that to the last two operand

Example: Infix 2 + (3 * 1) – 9 Equivalent post fix: 2 3 1 * + 9 -

Iterate the expression from left to right and keep on storing the
operands into a stack. Once an operator is received, pop the two
topmost elements and evaluate them and push the result in the stack
again
Algorithm to evaluate a postfix expression
Consider the expression: exp = “2 3 1 * + 9 -“

1. Scan 2, it’s a number, So push it into 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 3 1’

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’.
231*+9-

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’.

Scan 9, it’s a number. So we push it to the stack. The stack now


becomes ‘5 9’.
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’.
Convert the following expression into postfix expression and evaluate it

9 – ((3 * 4) + 8) / 4
Example: 3+5*(5/5)-2^2 == 3555/*+22^-
Algorithm : Conversion of Infix to Postfix

Scan the symbols of the expression from left to right and for each symbol.
1. If the symbol is an operand “ print that onto the screen”
2. If the symbol is a left parenthesis “ push it on the stack”
3. If symbol is a right parenthesis : push all the operators from the stack upto the first left parenthesis
and print them on the screen.
Discard the left and right parenthesis.
4.If symbol is an operator “ if the precedence of the operators in the stack are greater that or equal to the
current operators ,the pop the operator out of the stack and print them onto the screen and
push the current operator on to the stack.

else push the current operator onto the stack


A – (B / C + (D % E * F) / G)* H
3+5*(5/5)-2^2
Convert the following infix expressions to their postfix
equivalents:
(a)A – B + C

(b) A * B + C / D

(c) (A – B ) + C * D / E – C

(d) (A * B) + (C / D) – ( D + E)

(e) ((A – B) + D / ((E + F) * G))

(f) ( A – 2 * (B + C) / D * E) + F

(g) 14 / 7 * 3 – 4 + 9 / 2
Convert the expression given below into its corresponding
postfix expression and then evaluate it.

10 + ((7 – 5) + 10)/2
1075-10+2/+
Write a program to evaluate a post fix expression
Write a program to convert infix to post fix expression.

Note: will write program after IAT 1


(module 6)
Prefix notation (Polish notation)

prefix notation is evaluated from left to right

•The only difference between a postfix notation and a prefix notation is that in a prefix notation, the operator is
placed before the operands.

For example, if A+B is an expression in infix notation, then the corresponding expression in prefix
notation is given by +AB.

•While evaluating a prefix expression, the operators are applied to the operands that are present immediately on
the right of the operator.

•prefix expressions do not follow the rules of operator precedence and associativity, and even brackets cannot
alter the order of evaluation
Algorithm to convert infix expression into prefix expression

Method 1
Method 2
Example:

infix expression (A – B / C) * (A / K – L)

Step 1: Reverse the infix string. Note that while reversing the string you must
interchange left and right parentheses. (L – K / A) * (C / B – A)

Step 2: Obtain the corresponding postfix expression of the infix expression


obtained as a result of Step 1. The expression is: (L – K / A) * (C / B – A)

[L – (K A /)] * [(C B /) – A] = [LKA/–] * [CB/A–] = L K A / – C B / A – *

Step 3: Reverse the postfix expression to get the prefix expression Therefore,
the prefix expression is * – A / B C – /A K L
Algorithm for evaluation of a prefix expression
Find the prefix expression for following and evaluate the same

10+((7-5)+10)/2
Sol:+10/+-75102
Find prefix and postfix equivalent of following

A*(B*C+D*E)+F
Write a program to evaluate a prefix expression
Write a program to convert infix to prefix expression.

Note: will write program after IAT 1


(module 6)
Parentheses Checker

Stacks can be used to check the validity of parentheses in any algebraic

expression.

example:

An algebraic expression is valid if for every open bracket there is a corresponding

closing bracket.

For example, the expression (A+B} is invalid but an expression {A + (B – C)} is valid.
Write a program to check nesting of parentheses
using a stack.

Check number of left brackets equal to number of right brackets

For every left bracket there must be a right bracket of same type
Algorithm

• Create an empty stack


•Scan the symbol from left to right
•If the symbol is left bracket push it to the stack
•If the symbol is right bracket
if the stack is empty : “Invalid expression “, “ excess right bracket
else pop an element from the stack
if popped bracket dose not matched with the right bracket
then invalid exp” bracket not matching”

•After scanning if stack is empty “ valid expression” else “invalid expression”


EX : (A*(B-C) *{D-E}/F)
#include <stdio.h>
#include <stdlib.h> char pop();
#include <conio.h> void main()
{
#include <string.h>
char exp[MAX],temp;
#define MAX 10 int i, flag=1;
int top = –1; clrscr();
int stk[MAX]; printf("Enter an expression : ");
void push(char); gets(exp);
for(i=0;i<strlen(exp);i++)
{
if(exp[i]=='(' || exp[i]=='{' || exp[i]=='[')
push(exp[i]);
if(exp[i]==’)’ || exp[i]==’}’ || exp[i]==’]’)
if(top == –1)
flag=0;
else
{
temp=pop();
if(exp[i]==')' && (temp=='{' || temp=='['))
flag=0;
if(exp[i]=='}' && (temp=='(' || temp=='['))
flag=0;
if(exp[i]==']' && (temp=='(' || temp=='{'))
flag=0;
}
}
if(top>=0)
flag=0;
if(flag==1)
printf("\n Valid expression");
else
printf("\n Invalid expression");
}
void push(char c)
char pop()
{
{
if(top == (MAX–1))
if(top == –1)
printf("Stack Overflow\n");
printf("\n Stack Underflow");
else
else
{
return(stk[top––]);
top=top+1;
}
stk[top] = c;
}
}

You might also like