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

Unit III Ppt

Uploaded by

s21570028
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)
32 views

Unit III Ppt

Uploaded by

s21570028
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/ 68

Department of Electronics and Telecommunication Engineering

Unit-3
Stack and Queue

By
Siddhasen R Patil
Course Outcomes
CO3:
• On completion of the course, learner will be able to
develop applications of stack and queue using array.
Syllabus
• Stack:
– Concept
– Basic Stack operations
– Array representation of stack
– Stack as ADT
– Stack Applications:
• Reversing data,
• Arithmetic expressions conversion and evaluation.

• Queue:
– Concept
– Queue operations
– Array representation of queue
– Queue as ADT
– Circular queue
– Priority Queue
– Applications of queue:
• Categorizing data
• Simulation of queue.
Stack
• Concept:
Stack
• Basic Stack Operations:
– Push: Add an element to the top of a stack.

– Pop: Remove an element from the top of a stack.

– IsEmpty: Check if the stack is empty.


• Return either True (If stack is empty) or False (If stack is not empty).

– IsFull: Check if the stack is full.


• Return either True (If stack is full) or False (If stack is not full).

– Peek: Get the value of the top element without removing it.

– Size: Returns the number of elements in the stack.


Stack
• Basic Stack Operations:

Stack Operation Stack Content Return Value


s.isEmpty() [] True
s.push(10) [10]
s.push(22) [10,22]
s.push(36) [10,22,36]
s.size() [10,22,36] 3
s.pop() [10,22] 36
s.peek() [10,22] 22
s.isFull [10,22] False
Array Representation of Stack
• Algorithm
1. Initialize Stack
2. Display Menu: 1.Push, 2.Pop, 3.Display, 4.Exit
3. Read Choice
4. If Choice=1
Call Push Function
If Choice=2
Call Pop Function
If Choice=3
Call Display Function
If Choice=4
Exit from Program
Default
Display invalid Choice
4. Read Choice again
5. If Choice in between 1 to 3
Repeat step 3
Else
Stop
Array Representation of Stack
#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top = -1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
Array Representation of Stack
do
case 3:
{ {
printf("\n Enter the Choice:"); display();
break;
scanf("%d",&choice);
}
switch(choice) case 4:
{ {
case 1: printf("\n\t EXIT POINT ");
{ break;
push(); }
default:
break;
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
} }
case 2: } while(choice!=4);
{ return 0;
pop(); }
break;
}
Array Representation of Stack
void push()
{
if(top>=n-1)
printf("\n\tSTACK is over flow");
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top] = x;
}
}
Array Representation of Stack
void pop()
{
if(top<=-1)
printf("\n\t Stack is under flow");
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
Array Representation of Stack
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
}
Stack as ADT
• Abstract Data Types:
– An ADT is a mathematical model of a data
structure
– An ADT specifies
• The type of data stored
– int, float, char,
• The operations supported on them
– push. pop, read
Stack Applications
Reversing data:
#include <stdio.h>
int top,stack[10]; void push(char x)
main() {
{ if(top == 9)
char str[]=“ABCDE"; printf("stack overflow");
int len = 5; else
int i; stack[++top] = x;
}
for(i=0;i<len;i++)
push(str[i]); void pop()
{
for(i=0;i<len;i++) printf("%c",stack[top--]);
pop(); }
}
Arithmetic Expressions Conversion and
Evaluation

• The stack is very effective in evaluating arithmetic expressions.

• Mathematical expressions are generally represented in Infix


notation,
– In this each operator is written between two operands
– i.e. A + B

• Prefix notation: In this notation the operator is placed before its two
operands.
– i.e. +AB

• Postfix notation: In this notation the operator is placed after its two
operands.
– i.e. AB+
Arithmetic Expressions Conversion and
Evaluation
• There are 4 levels of precedence for binary operators as given
below:
– 4. Parenthesis { }, ( ), [ ] Highest
– 3. Exponentiation (^)
– 2. Multiplication (*) and division (/)
– 1. Addition (+) and Subtraction (-) Lowest

– The Operators from same precedence are evaluated from


left to right.
Arithmetic Expressions Conversion and
Evaluation
• Infix to Postfix Notation:

Infix Postfix
A+B
A+B*C
(A+B)*C
C/(D+E)+F
A+B*C+D
(A + B) * (C + D)
A*B+C*D
A+B+C+D
(A-B)*[C/(D+E)+F]
Arithmetic Expressions Conversion and
Evaluation
• Infix to Postfix Notation:

Infix Postfix
A+B AB+
A+B*C ABC*+
(A+B)*C AB+C*
C/(D+E)+F CDE+/F+
A+B*C+D ABC*+D+
(A + B) * (C + D) AB+CD+*
A*B+C*D AB*CD*+
A+B+C+D AB+C+D+
(A-B)*[C/(D+E)+F] AB- CDE +/F +*
Arithmetic Expressions Conversion and
Evaluation
• Infix to Prefix Notation:

Infix Prefix
A+B
A+B*C
(A+B)*C
C/(D+E)+F
A+B*C+D
(A + B) * (C + D)
A*B+C*D
A+B+C+D
(A-B)*[C/(D+E)+F]
Arithmetic Expressions Conversion and
Evaluation
• Infix to Prefix Notation:

Infix Postfix
A+B +AB
A+B*C +A*BC
(A+B)*C *+ABC
C/(D+E)+F +/C+DEF
A+B*C+D ++A*BCD
(A + B) * (C + D) *+AB+CD
A*B+C*D +*AB*CD
A+B+C+D +++ABCD
(A-B)*[C/(D+E)+F] *-AB+/C+DEF
Algorithm for Infix to Postfix Conversion
using Stack
• Step 1 : Push “(“onto Stack, and add “)” to the end of X.

• Step 2 : If the scanned character is an operand,


– Append it with final Infix to Postfix string.

• Step 3 : If the scanned character is the operator and the Stack is


empty Or contains the '(' symbol,
– Push the operator into the Stack.

• Step 4 : If the scanned operator has higher precedence than the


existing precedence operator in the Stack Or if the Stack is
empty,
– Then put it on the Stack.

• Step 5 : If the scanned operator has lower precedence than the


existing operator in the Stack,
– Pop all the Stack operators and Push them to Postfix string.
– After that, push the scanned operator into the Stack.
Algorithm for Infix to Postfix Conversion
using Stack
• Step 6 : If the scanned character is a left bracket '(',
– Push it into the Stack.

• Step 7 : If we encountered right bracket ')',


– Pop the Stack and print all output string character until '(' is encountered
– and discard both the bracket.

• Step 8 : Repeat all steps from 2 to 8 until the infix expression is


scanned.
• Step 9 : Pop all the operators from the Stack until stack is not
empty.
Algorithm for Infix to Postfix Conversion
using Stack
• Convert the following Infix to Postfix using algorithm
A+(B*C))
Sr. Symbol Stack Output
No.
(
1 A ( A
2 + (+ A
3 ( (+ ( A
4 B (+ ( AB
5 * (+ ( * AB
6 C (+ ( * ABC
7 ) (+ ABC*
8 ) ( ABC*+
9 ) End
Algorithm for Infix to Postfix Conversion
using Stack
• Convert the following Infix to Postfix using algorithm
A + B * C + D)

Sr. Symbol Stack Output


No.
(
1 A ( A
2 + (+ A
3 B (+ AB
4 * (+* AB
5 C (+ * ABC
6 + (+ ABC*+
7 D ( ABC*+D +
8 ) End
• Convert the following Infix to Postfix using algorithm
(A + B) * (C + D)
Sr. Symbol Stack Output
No.
( (
1 ( ((
2 A (( A
3 + ((+ A
4 B ((+ AB
5 ) ( AB+
6 * (* AB+
7 ( (*( AB+
8 C (*( AB+C
9 + (*(+ AB+C
10 D (*(+ AB+CD
11 ) (* AB+CD+
12 ) AB+CD+*
End
C Program for Infix to Postfix Conversion

#include<stdio.h>
#include<conio.h>
main()
{
char in[20], po[20], st[20];
int top = -1, i, n, j=0;
printf(“\nEnter total No. of symbols in Infix: ”);
scanf(“%d”, &n);

printf(“Enter all symbols of Infix:”);


for (i=0;i<n;i++)
scanf(“%c”, & in[i]);

in[i] = ‘)’;
st[++top]=‘(‘;
C Program for Infix to Postfix Conversion
for (i=0; top != -1; i++)
{
if (in[i]== ‘(‘)
st[++top]=‘(‘;
else if (in [i] == ‘+’ || in[i] == ‘-’)
{
while (st[top] != ‘(‘)
{
po[j] = st[top]; top--; j++;
}
st[++top] = in[i];
}
else if (in [i] == ‘*’ || in[i] == ‘/’)
{
while (( st[top] != ‘(‘ ) && ( st[top] != ‘+‘ ) && ( st[top] != ‘-‘ ))
{
po[j] = st[top--]; j++;
}
st[++top] = in[j];
}
C Program for Infix to Postfix Conversion
else if (in[i] == ‘)’)
{
while (st[top] != ‘(‘)
{
po[j]= st[top--]; j++;
}
top --;
}
else
{
po[j] = in [i]; j++;
}
}
for (i=0; i<j; i++)
printf (“%c”, po[i]);
getch( );
return(0);
}
Algorithm for Infix to Prefix Conversion
using Stack
• Step 1 : Reverse the Infix expression also change the ‘(‘ by ‘)’ and ‘)’
by ‘(‘.
– And Push “(“onto Stack, and add “)” to the end of X.

• Step 2 : If the scanned character is an operand,


– Append it to Prefix string.

• Step 3 : If the scanned character is the operator and the Stack is empty
Or contains the '(' symbol,
– Push the operator into the Stack.

• Step 4 : If the scanned operator has higher precedence than the


existing precedence operator in the Stack Or if the Stack is empty,
– Then put it on the Stack.

• Step 5 : If the scanned operator has lower precedence than the existing
operator in the Stack,
– Pop all the Stack operators and append them to Prefix string.
– After that, push the scanned operator into the Stack.
Algorithm for Infix to Prefix Conversion
using Stack
• Step 6 : If the scanned character is a left bracket ‘)',
– Push it into the Stack.

• Step 7 : If we encountered right bracket ‘(',


– Pop the Stack and print all output string character until ‘)' is encountered
– and discard both the bracket.

• Step 8 : Repeat all steps from 2 to 8 until the infix expression is


scanned.
• Step 9 : Pop all the operators from the Stack until stack is not
empty.
• Step 10 : Reverse the output string using stack and print it.
C Program for Infix to Prefix Conversion
#include<stdio.h>
#include<conio.h>
main()
{
char in[30], po[30], st[30]; To Reverse the equation:
int top = -1, i, n, j=0; for (i=0;in[i]!='\0';i++)
clrscr(); {
printf("Enter Infix Expression"); if(in[i]=='(')
scanf("%s",&in); st[++top]=')';
else if(in[i]==')')
st[++top]='(';
else
st[++top]=in[i];
}
for (i=0;top!=-1;i++)
{
in[i]=st[top--];
}
in[i] = ')';
st[++top]='(';
C Program for Infix to Prefix Conversion

for (i=0; top != -1; i++)


{
if (in[i]== '(')
st[++top]='(';
else if (in[i] == '+' || in[i] == '-')
{
while (st[top] != '(')
{
po[j] = st[top--]; j++;
}
st[++top] = in[i];
}
else if (in[i] == '*' || in[i] == '/')
{
while (( st[top] != '(' ) && ( st[top] != '+' ) && ( st[top] != '-' ))
{
po[j] = st[top--]; j++;
}
st[++top] = in[i];
}
C Program for Infix to Prefix Conversion
else if (in[i] == '^')
{
while (( st[top] != '(' ) && ( st[top] != '+' ) && ( st[top] != '*' )&& ( st[top] != '/' ) && ( st[top] != '-' ))
{
po[j] = st[top--]; j++;
}
st[++top] = in[i];
}
else if (in[i] == ')')
{
while (st[top] != '(')
{
po[j]= st[top--]; j++;
}
top --;
}
else
{
po[j] = in[i]; j++;
}
}
C Program for Infix to Prefix Conversion

top=-1;
for (i=0;i<j;i++)
{
st[++top]=po[i];
}
for (i=0;top!=-1;i++)
{
po[i]=st[top--];

}
printf("\nThe Prefix Equation of the given Infix equation is: ");
for (i=0;i<j;i++)
printf ("%c", po[i]);

getch ();
return (0);
}
Evaluation of Postfix Expression
Postfix Expression: 5 4 * 10 + 15 – 6 +

Symbol Stack Op1 Op2 Value


5 5
4 5, 4
* 5 4 20
20
10 20, 10
+ 20 10 30
30
15 30, 15
- 30 15 15
15
6 15, 6
+ 15 6 21
21
Algorithm for Infix to Prefix Conversion
using Stack
• Step 1 : Scan postfix array from left to right.

• Step 2 : If the operand is encountered, push it in stack.

• Step 3 : If operator is encountered then pop two elements


i.e. B = st[top] and A= Next st[top] and evaluate A operator B.

• Step 4 : Push result into stack.

• Step 5 : Repeat step 2 to 4 for the next element of the postfix array.

• Step 6 : If the postfix string ends then Print the result popped from
the stack and Display the result.
C Program to Evaluate Postfix Expression
main()
{
int n,st[30],top = -1, val, a, b, result, i=0;
char A[30];
clrscr();
printf(“Enter the string of Postfix Expression”);
scanf(“%s”,&A);
while ( A[i] != ‘\0’)
{
if (A[i] >= ‘0’ && A[i] <=‘9’)
{
val = A[i] – 48;
st[++top] = val;
}
C Program to Evaluate Postfix Expression

else if (A[i] == ‘+’ || A[i] == ‘-’ || A[i] == ‘*’ || A[i] == ‘/’ )


{
b = st[top--];
a = st[top--];
switch (A[i])
{
case ‘+’: result = a+b; break();
case ‘-’: result = a-b; break();
case ‘*’: result = a*b; break();
case ‘/’: result = a/b; break();
}
st[++top]=result;
} i++;
} result = st[top--];
printf(“The result of evaluation is %d”,result);
}
Evaluation of Prefix Expression
Prefix Expression: - * + 4 3 2 5

Symbol OpndStack Op1 Op2 Value


5 5
2 5, 2
3 5, 2, 3
4 5, 2, 3, 4
+ 5, 2 4 3 7
5, 2, 7
* 5 7 2 14
5, 14
- 14 5 9
9
Algorithm for Evaluation of Prefix using Stack

• Step 1 : Scan prefix array from right to left.

• Step 2 : If the operand is encountered, push it in stack.

• Step 3 : If operator is encountered then pop two elements


i.e. A = st[top] and B= Next st[top] and evaluate A operator B.

• Step 4 : Push result into stack.

• Step 5 : Repeat step 2 to 4 for the next element of the prefix array.

• Step 6 : Once the prefix string ends then Print the result popped
from the stack.
C Program to Evaluate Prefix Expression
#include<stdio.h>
#include<conio.h>
main()
{
int n, st[30], top = -1, val, a, b, result, i=0;
char A[30];
clrscr();
printf("Enter the string of Postfix Expression");
scanf("%s",&A);

for(i=0;A[i]!='\0';i++)
st[++top]=A[i];

for (i=0;top!=-1;i++)
A[i]=st[top--];

A[i]='\0';
C Program to Evaluate Postfix Expression
i=0;
while ( A[i] != '\0')
{
if (A[i] >= '0' && A[i] <= '9')
{
val = A[i] - 48;
st[++top] = val;
}
else if (A[i] == '+' || A[i] == '-' || A[i] == '*' || A[i] == '/')
{
a = st[top--];
b = st[top--];
switch (A[i])
{
case '+': result = a+b; break;
case '-': result = a-b; break;
case '*': result = a*b; break;
case '/': result = a/b; break;
}
st[++top]=result;
} i++;
}
C Program to Evaluate Postfix Expression
result = st[top--];
printf("\nThe result of evaluation is %d",result);

getch();
return(0);
}
Queue
• Concept:
– A queue in C is basically a linear data structure to store and
manipulate the data elements.

– It follows the order of First In First Out (FIFO).

– In queues, the first element entered into the array is the first
element to be removed from the array.
Queue
• Operations :
– isEmpty(): To check if the queue is empty

– isFull(): To check whether the queue is full or not

– dequeue(): Removes the element from the front side of the queue

– enqueue(): It inserts elements to the end of the queue

• Pointers
– Front: Pointer element used to locate the location of first element of
the queue

– Rear: Pointer element used to locate the location of the last element of
the queue.
Array Representation of Queue
• Algorithm
1. Initialize Queue
2. Display Menu: 1. Insert, 2. Remove, 3.Display, 4.Exit
3. Read Choice
4. If Choice=1
Call Insert Function
If Choice=2
Call Remove Function
If Choice=3
Call Display Function
If Choice=4
Exit from Program
Default
Display invalid Choice
4. Read Choice again
5. If Choice in between 1 to 3
Repeat step 3
Else
Stop
Algorithm for Insertion Function
Step 1:If (rear = max) then
a. Print Q is full
Else
a. if (front = -1)
i. front = 0
ii. rear = 0
b. Store new element at Q[rear];
c. Rear = rear+1
Algorithm for Delete Function
Step 1:
If front = rear
Print Q is empty
Else
Print the deleted element Q[front];
Front = front + 1
Algorithm for Read Queue Function
Step 1:
If front = rear
Print Q is empty
Else
a. Repeat step b until (i = Front; i <= Rear; i++)
b. Print Q[i];
Array Representation of Queue
#include<stdio.h>
#include<conio.h>
int main()
{
int queue[10], ch, front = -1, rear = -1, i;
clrscr();
printf("\n1.Insert \n2.Delet \n3.Display \n4.Exit");
printf("\nEnter the Choice:");
scanf("%d",&ch);
Array Representation of Queue
do
{
switch(ch)
{
case 1:
if(rear == 10)
printf("\n Queue is Full");
else
{
if (front == -1)
{
front++; rear++;
}
printf("\n Enter no ");
scanf("%d", &queue[rear++]);
} break;
Array Representation of Queue
case 2:
if(front == rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d", queue[front++]);
} break;
Array Representation of Queue
case 3:
if(front == rear)
printf("\n Queue is Empty");
else
{
printf("\nQueue Elements are:\n ");
for(i=front; i<rear; i++)
printf("%d\n",queue[i]);
} break;
case 4:
return(0);
default:
printf("Wrong Choice: please enter correct option");
}
Array Representation of Queue
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
printf("\nEnter the Choice:");
scanf("%d",&ch);
} while(ch!=4);
return 0;
}
Circular Queue

• A circular queue is the extended version of a regular queue.

• In this the last element is connected to the first element.

• Thus forming a circle-like structure.

• In a normal queue, after a bit of insertion and deletion, there


will be non-usable empty space.
Algorithm for Circular Queue
1. Initialize Queue
2. Display Menu: 1. Insert, 2. Remove, 3.Display, 4.Exit
3. Read Choice
4. If Choice=1
Call Insert Function
If Choice=2
Call Remove Function
If Choice=3
Call Display Function
If Choice=4
Exit from Program
Default
Display invalid Choice
4. Read Choice again
5. If Choice in between 1 to 3
Repeat step 3
Else
Stop
Algorithm for Insertion Function
• Step 1:
a. If((front == 0 && rear == MAX-1) || (front == rear+1))
Print Queue is Full
b. Else
If (front = -1)
Front=0 and Rear=0
Else
If (rear=Max-1)
Rear=0
Else
Rear = Rear+1

c. Scan new element and store it at Q[Rear]


Algorithm for Delete Function
Step 1:
a. If Front= -1
Queue is Empty
b. Else
i. Print the deleted element from Q[front]
ii. If front = rear
Front = -1 and Rear = -1
iii. Else
If (front = Max-1)
Front = 0
Else
Front = front + 1
Algorithm for Read Queue Function
Step 1: Int f = front and r = rear
Step 2:
a. If (f=-1)
Print Queue is empty
b. Else
Print (Queue elements are:)
i. If (f <= r) then repeat following step till (f <=r)
Print Q[f++]
ii. Else repeat next step till (f<= Max-1)
Print Q[f++]

F=0
Repeat following step till (f<=rear)
Print Q[f++]
C-Program for Circular Queue
#include<stdio.h>
#include<conio.h>
# define MAX 5
int cqueue_arr[MAX];
void insert(void);
void deletion (void);
void display (void);
int front = -1;
int rear = -1;

int main()
{
int choice;
clrscr();
printf("\n1.Insert \n2.Delete \n3.Display \n4.Quit");
printf("Enter your choice : ");
scanf("%d",&choice);
C-Program for Circular Queue
do
{
switch(choice)
{
case 1 :
insert();break;
case 2 :
deletion(); break;
case 3:
display();break;
case 4:
return (0); break;
default:
printf("Wrong choicen");
}
printf("\n1.Insertn \n2.Deleten \n3.Displayn \n4.Quit");
printf("\nEnter your choice : ");
scanf("%d",&choice);
}while(choice!=4);

return (0);
}
C-Program for Circular Queue
void insert()
{
if((front == 0 && rear == MAX-1) || (front == rear+1))
printf("\nQueue Overflow");
else
{
if(front == -1)
{
front = 0;
rear = 0;
}
else
{
if(rear == MAX-1)
rear = 0;
else
rear = rear+1;
}
printf("\nInput the element for insertion in queue : ");
scanf("%d", & cqueue_arr[rear]);
}
}
C-Program for Circular Queue
void deletion()
{
if(front == -1)
printf("Queue Underflown");
else
{
printf("Element deleted from queue is : %d",cqueue_arr[front]);
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
if(front == MAX-1)
front = 0;
else
front = front+1;
}
}
}
C-Program for Circular Queue
void display()
{
int f = front, r = rear;
if(front == -1)
{
printf("\nQueue is empty");
}
else
{
printf("\nQueue elements :");
if( f <= r )
{
while(f <= r)
{
printf("%d ",cqueue_arr[f]);
f++;
}
}
else
{
C-Program for Circular Queue
else
{
while(f <= MAX-1)
{
printf(“ %d ",cqueue_arr[f]);
f++;
}
f = 0;
while(f <= r)
{
printf(“ %d ",cqueue_arr[front_pos]);
f++;
}
}
}
}
Priority Queue
• In priority Queue each element has its own priority.

• In Priority Queue data who has highest priority remove from the Queue
first or processed first and second highest priority element after it and so
on.

• If priority is same for two elements then data remove on the basis of first
come first serve.
Priority Queue
Application of Queue
•Categorizing data
– Categorization is the process of dividing the things into groups whose
members are in some way similar to each other.

– So data could then be categorized as high sensitivity data, medium sensitivity


data and low sensitivity data.

– The example of Categorizing data is the Multiple Queue.


▪ Multi queue is data structure in which multiple queues are maintained.
▪ This type of data structures are utilized for process scheduling.

You might also like