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

Stack & Queue

The document discusses stacks, which are linear data structures where insertion and deletion only occur at one end. It covers stack operations like push and pop, provides examples of stack usage, and includes sample code to demonstrate stack functions. Key applications of stacks mentioned are recursion, Polish notation, and stack machines.

Uploaded by

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

Stack & Queue

The document discusses stacks, which are linear data structures where insertion and deletion only occur at one end. It covers stack operations like push and pop, provides examples of stack usage, and includes sample code to demonstrate stack functions. Key applications of stacks mentioned are recursion, Polish notation, and stack machines.

Uploaded by

AsHu Xd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Data Structure -1CE2303

UNIT- II
Stack Data Queue

After completion of array the most important data structure is


STACK. The stack structure has some operation, how the data can be
inserted, retrieved and remove from it.

 Definition:- Stack is a linear structure in which insertion and


deletion are always done at one end, called the TOP.

In stack the element insert first it can be remove last that means the
stack is call “Last in First out” (LIFO). Or some time we call it first in last
out (FILO).

Good life example of stack is the bunch of dinner plate. In that person
want to take dinner then he or she has to take the dish which is on TOP
but logically the TOP dish is exactly added (inserted) last recently on the
bunch by the dish washer. If you want to put it at bottom of bunch then
you have to remove the entire dish on top of it to reach it. So that is the
example of stack which show the last come first serves (LCFS) or (LIFO).

There are two basic operation can be performed on a stack is call the,

1. Push operation ( insertion of element)


2. Pop operation ( deletion of element)

“Other two operation peep and change are also the operation of stack but
in our syllabus they are not included so we will not discuss regarding
them.”

For all the operation of stack it has a one pointer is called TOP pointer and
it is initially located at 0 positions and step by step it will increment by
one (TOP + 1) when we insert the element in it.

For inserting the element in stack first of all we have to check the space
of stack means there are space in stack or stack is already full. That we
come to know by the position of TOP pointer. i.e. the TOP pointer value
is below then the size of Stack then we can say there are some space
available in it otherwise we can’t enter any more element in it.
 Algorithm PUSH ( N, TOP)

Purpose :- to insert the new element to stack


TOP :- the top most position of stack
N :- Max Size of array
S :- Array Representing the stack
X :- the element which you want to enter
[ Check for overflow ]
If (TOP > = N) then
Write Stack is overflow
Return.
[Increment the TOP ]
TOP  TOP +1
[ Insert the element ]
S [TOP]  X
[ Finished ]
Return
Here first of the entire overflow condition will check and if the space is
available then the top is increment by one and then the new element can
enter at the new located position.
Initially TOP = 0 and stack empty one by one element will be insert
through the push operation and the top is incremented one by one
sequentially.
M
K K
Z Z Z
Y Y Y Y
X X X X X
Top=0 Top=1 Top=2 Top =3 Top= 4
Top++ Top ++ Top++ TOP++ Top ++
Insert X insert Y insert Z insert K insert M

Now the value of Top is become the largest size of stack means 5 so we
can’t insert any more variable to it so if we again try to insert then the
stack is reply overflow.

 POP operation of Stack:-

Same as push operation when we want to delete some element


from stack then we are using the pop operation. In that first of the entire
element is not to be indicated for delete because as per the characteristic
of stack the latest top most element must be deleted.
 Algorithm POP (N, TOP)

Purpose :- to delete the element from top of the stack.


Top :- represent the TOP most element position in stack
S :- represent the stack Array
X :- element which we want to delete
[check if stack is empty]
If ( Top = = 0)
Write “Stack is under flow”
Return
[delete the element]
X s [Top]
[decrement the Top pointer ]
Top  Top – 1
[ Finished]
Return(x)
M M
K K K
Z Z Z Z
Y Y Y Y Y
X X X X X
Top=5 Top=4 Top=3 Top =2 Top= 4
Top-- Top -- Top-- TOP-- Top ++
Delete M Delete K Delete Z Delete Y Delete X
Now after the fifth operation of pop the stack has not longer any value or
element for delete. So again we try to pop from the stack then the value
of Top is 0 so it will reply the stack is under flow so no more value is
available for delete. This is the procedure for delete the element from
stack.

After completing the two operations there are two more operation can be
done on stack like peep and change operation. Through the peep
operation we can find out the value in some particular position. And the
change operation we can do the change or we can put the new element
instead of the element which found through the peep operation.

Program for understanding all the operation of stack.

#include<stdio.h>
#include<conio.h>
#include<process.h>
#define n 5
int top=0,stack[n];
void main()
{
int choice;
clrscr();
void push(); /* Define the operation push
void pop(); /* Define the operation pop
void display(); /* Define the operation Display
printf(“\n 1.PUSH \n 2.POP\n 3.DISPLAY\n 4.EXIT\n”);
printf(“Enter Choice What u Want to Do?”);
scanf(“%d”, &choice);
do
{
switch(choice)
{
case 1:
{
push();

break;
}
case 2:
{
if(top==0)
{
printf(“\n The Stack Underflow”);
}
else
{
pop();

}
break;

}
case 3:
{
display();
break;
}
case 4:
exit(0);
break;
}
printf(“\n Enter Choice What u Want to Do?”); /* doing the
same process
again means
continue the
program
scanf(“%d”, &choice);
}while(choice!=4);
getch();
}
void push()
{
if(top>=n)
{
printf(“\n The Stack Is Full”);
}
else
{
int x;
top=top+1;
printf(“\n Enter Element U Want To Push”);
scanf(“%d”, &x);
stack[top]=x;
}
}
void pop()
{
top=top-1;
printf(“\n The removed element is:%d”, stack[top+1]);
}
void display()
{
int I;
for(i=top;i>0;i--)
{
printf(“\n %d”, stack[i]);
}
}
Output :-
Push
Pop
Display
Exit
Enter Choice What u Want to Do? Enter Choice What u Want to Do?
1
Enter Element U Want To Push
22
Enter Choice What u Want to Do?
1
Enter Element U Want To Push
33
Enter Choice What u Want to Do?
1
Enter Element U Want To Push
44
Enter Choice What u Want to Do?
2
The removed element is 44
Enter Choice What u Want to Do?
3
33
22
Enter Choice What u Want to Do?
4
Exit from program
 Application of Stack:-

Basically there are three applications.

1. Recursion
2. Polish notation
3. stack machine
 Recursion:- Recursion that means the function called itself. The
process will repeat number of time but at one stage it will be stop.

Let us check one example of recursion and the roll of stack in it.
Find the factorial of 5
5!= 5 * 4!
= 4 * 3!
= 3 * 2!
= 2 * 1!
=1
Here we know that the 1! = 1 means it is the indication of stop and the
result will be display over there. In above the 5! Calls to 4! And 4! Calls to
3! And so on. Here the main idea of repeating is recursion so using
recursion calculation of anything can be done easily. But be carefully each
problem cannot solve using recursion.
When same procedure is require to do for more time with same value
with particular termination then only it can be solved by recursion.

 Polish Notation:-
Generally the expression involves the use of operand and operator
symbol. And we write the operator in between the two operand, before
the operand or after the operand it becomes the polish notation.

There are three types of polish notation:-

1. Prefix notation
2. Infix notation
3. Postfix notation

Suppose the A and B two operand and the + is operator so we can write
following way.

 Infix notation:- if we write the operator in between the operand


then is call the infix notation.

Ex. A + B
Operand operator operand

 Postfix notation: - if we write the operator after the operand then


is call the postfix notation.

Ex. AB+
Operand operand operator

 Prefix Notation:- if we write the operator before the operand then


is call prefix notation.

Ex. +AB
Operator operand operand

 Conversion of infix to postfix (suffix or reverse polish).

Stack can be used for forming a expression. Means from infix to


postfix or from one type to another type. It can also be used to evaluate
such type of expression we see by one example in detail.

First of all we assign the precedence of four arithmetic operators in


the following table.

Symbol Precedence Rank


+, - 1 -1
*, / 2 -1
^, 3, -1 -- --
A, b,c 4 +1
# 0 --
Assume the stack initialized by one value is # and its precedence is 0 is
the less then to all other given in table.
Ex. Check the given string is valid or not using stack or convert the given
infix expression to postfix expression using stack.

 Infix string: - a + b * c- d / e * h

Char Scan Content of Reverse polish Rank


#
A #a -- --
+ #+ A 1
B #+b A 1
* #+* Ab 2
C #+*c Ab 2
- #- Abc*+ 1
D #-d Abc*+ 1
/ #-/ Abc*+d 2
E #-/e Abc*+d 2
* #-* Abc*+de/ 2
H #-*h Abc*+de/ 2
# ## Abc*+de/h*- 1
In above operation at the end if we found the rank is 1 then the given
infix expression is valid otherwise it is invalid.

 Some other example of the infix expression.

Infix Suffix( Postfix) Rank Valid / Invalid


A+*B Ab*+ 0 Invalid
Ab+c Abc+ 2 Invalid
a-b*c Abc*+ 1 Valid
A+b/d- Abd/+- 0 Invalid
(a+b)*(c-d) Ab_cd-* 1 Valid
Same conversion of expression from infix to post fix but with parentheses
then again we have to arrange the priority table and some particular
condition for that. The table shown below is a base for conversion.

 Translate of infix to postfix with parentheses

Symbol Input precedence Stack precedence Rank


+, - 1 2 -1
*,/ 3 4 -1
^ 6 5 -1
Variable 7 8 1
( 9 0 --
) 0 -- --
 Translate the infix string (a+b^c^d)*(e+f/d)) to reverse
polish

Stack is initialized by the symbol (its input priority is 9 and stack priority
is nothing. Step by step we insert the character and convert it into
reverse polish notation.

Input Content of New reverse polish Sum of


(
( (( -- --
A ((a -- --
+ ((a+ -- --
B ((+b A 1
^ ((+^ Ab 2
C ((+^c Ab 2
^ ((+^^ Abc 3
D ((+^^d Abc 3
) ( Abcd^^+ 1
* (* Abcd^^+ 1
( (*( Abcd^^+ 1
E (*(e Abcd^^+ 1
+ (*(+ Abcd^^+e 2
F (*(+f Abcd^^+e 2
/ (*(+/ Abcd^^+ef 3
D (*(+/d Abcd^^+ef 3
) (* Abcd^^+efd/+ 2
) -- Abcd^^+efd/+* 1
At the end of the procedure we found the rank is one it means the given
expression is valid. If we get les then one rank then we can tell the give
expression is not valid.

 Stack Machine:-

In some electronics machine has very fast register provided for buffering
purpose. When the calculation are to be done then the thing will not be
enough so using stack operation for the values of these register
calculation can be easily done and the limitation of the few no. of register
can easily overridden. Such machine can use the concept of stack for
calculation.
 Queue Data Structure

Queue means a standing queue of person waiting for the railway


reservation is the best example of the same. The person arrives at ticket
window and start the queue. Before that there is no queue. There is no
beginning and no end of queue. A next person arrives and joins at the
end of the queue. Generally new person will be joining at the end of the
queue.

i.e insertion of new element will be always at the end of queue. First
person in the queue will take the ticket and go away means remove
(delete) from the queue. And the next person of queue will be given the
service.

Defination:-

The data structure in which element are insertion and deletion occur at
the opposite end is call queue Data Structure.

Here the element come first must be delete first so this data structure is
call the first in first out (FIFO) or first come first serve (FCFS)

X Y Z A

Simple Queue

Delete the element Element is inserted

For managing the insertion and deletion there are two pointer front and
rear. The rear pointer is work for insertion of new element.

For insertion process initially pointer R is 0 and one by one they


increment when we insert the value to the queue. Very first insertion we
have to set the front pointer also as 1 from 0. Then after we only
increment the rear pointer for every insertion.

For deletion operation the pointer front F initially 1 because at very first
insertion we set the from pointer. One by one it will be increment when
we delete he element from queue. When again both pointers become
same they are initialized 0 again.

Initially both the pointer is 0

R=0
F=0
We insert the first element X to the queue then the rear pointer is
incremented by one and become 1 and the front pointer also set as one
very first time.
X
R=1
F=1
Insert second element Y to queue then naturally the rear pointer is
incremented by one and become 2. The font pointer remains as it is 1.

X Y
Similarly F=1 R=2

X Y Z
F=1 R=3

X Y Z A
F=1 R=4

Now we want to delete element from queue then the first element X will
be deleted first due to characteristic of queue and the front pointer is
incremented by one and become 2
Y Z A
F=2 R=4
Again we want to delete the element then Y will be deleted and the front
pointer become 3.
Z A
F=3 R=4
Similarly we can delete the element but when the last element id deleted
form the queue then both the pointer becomes same so both will be
reinitialized again and become 0.
A
F=4 ,R =4

F=0
R=0
Basically queue performed two operations
insert the element to the queue
Delete the element from queue
 Algorithm QInsert (Q,F,R,N,Y)

F : - front pointer
R : - Rear Pointer
Q : - Array Representing Queue
N : - Max numbers of array elements
Y : - element to be inserted

[ check for queue if full]


If R > = N then
Write “queue is overflow”
Return
[increment the rear pointer]
R= R + 1
[insert the element]
Q[R] = Y
[Is front pointer properly set?]
If F = 0 then
F=1
[Finished]
Return

 Algorithm Qdelete( Q,F,R)

Purpose : - to delete the element from queue


F : - Front end of the queue
R : - rear end of the queue
Q : - Array representing the queue
[check for underflow]
If F=R=0 then
Write “queue is empty”
Return
[delete the element]
Y = Q [F]
[check if single element]
If F= = R then
F=R=0
Return
[Set the front pointer]
F = F +1
[Finished]
Return
 Program for understanding the operation of Simple Queue

#include<stdio.h>
#include<conio.h>
#include<process.h>
void insert();
void Delete();
void display();
void exit();
int r=0,n;
int f=0;
int q[10];
void main()
{
int ch;
clrscr();

printf(“enter the queue size \n”);


scanf(“%d”,&n);
while(1)
{ printf(“\n1.INSERT \n2.DELETE \n3.DISPALY \n4.EXIT”);
printf(“\nEnter your choice:”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: insert();
break;
case 2: Delete();
break;
case 3: display();
break;
case 4: exit(0);
break;
}
}
getch();
}
void insert()
{
int no;
printf(“Enter the num:”);
scanf(“%d”,&no);
if(r>=n)
{
printf(“Overflow…......overflow….........overflow”);
return;
}
r=r+1;
q[r]=no;
if(f==0)
{
f=1;
}
}
void Delete()
{
if(f==0)
{
printf(“Underflow….......underflow…........underflow”);
return;
}
printf(“Deleted element is %d”,q[f]);
if(f==r)
{
f=0;
r=0;
}
else
{
f=f+1;
}
}
void display()
{
for(int i=f;i<=n;i++)
printf(“\n%d “,q[i]);
}

 Output:-

Enter the queue size


5
Insert
Delete
Display
Exit
Enter your choice
1
Enter the num
22
Enter your choice
1
Enter the num
33
Enter your choice
1
Enter the num
44
Enter your choice
1
Enter the num
55
Enter your choice
1
Enter the num
66
Enter your choice
1
Enter the num
77
Overflow…......overflow….........overflow
Enter your choice
2
Deleted element is 22
Enter your choice
2
Deleted element is 33
Enter your choice
3
44
55
66
Enter your choice
4
Exit from program

 Circular Queue

We have seen in simple queue there are two pointer, rear and front which
are used for insert and delete respectively. But here the end of queue are
different means once we use the queue we can’t use it again but in
circular queue the front end is join with rear end so the queue become
like circle so it called the circular queue and the rear pointer reach at the
end and the earlier element had deleted from the queue then the rear
pointer can be reinitialized again and insert the new element after the end
also.
Graphical representation of circular queue is

F=0
R=0
Circular Queue

F=0
R=0
In above queue we represent with example suppose initially both pointer
are initialized with 0. If we insert the element A then rear pointer become
1 and for first time the front pointer also set as 1.
A
F=1
R=1
Now we insert the second element B to the queue then the rear pointer
will be increment by one and front remain as it is.
A B
F=1 R=2
Now insert the C third element to the queue we found below
A B C
F=1 R=3
Similarly we found the position on fifth element like below
A B C D E
F=1 R=5
Now we want to enter again new element F then it will display overflow
but before insert if we delete some element from queue then it is possible
to insert like that
Delete the element from queue
B C D E
F=2 R=5
Again delete the element
C D E
F=3 R=5
Now we want to insert the F then we can because the earlier block are
available in queue and this queue is circular so it is possible.
Insert the F to queue
F C D E
R=1 F=3

“ So it is the main advantage of the circular queue that you can reuse the
empty space once again created by the deletion of other element of the
queue that is not possible in simple queue. “
Algorithm Cqinsert ( F, R, CQ, N, Y)
F : - front end of circular queue
R : - Rear end of circular Queue
CQ : - Array representing the circular Queue
N : - Max Size of array
Y - Element to be inserted
[set the rear pointer]
If R=N then
R=1
Else
R = r+1
[Check for overflow]
If F = R then
Write “overflow”
Return
[Insert element]
Cq[r] = Y
[Set the front pointer]
If f=0 then
F=1
[Finished]
Return
Algorithm Cqdelete (F, R,CQ, N)
F : - front end of circular Queue
R : - Rear end of circular Queue
CQ : - Array representing the circular Queue
N : - Max Size of array
[ check for empty]
If F = 0 then
Write “empty Circular Queue”
Return
[delete the element]
Y = CQ [F]
[Check for single element]
If F = R then
F =R = 0
Return
[Set the front pointer]
If F = N then
F=1
Else
F = F +1
[Finished]
Return

 Double ended queue:-

The queue which can removes and inserts the element from both ends is
called the double ended queue.

 Priority Queue:-

Priority queue is a Data structure which inserts the element in based on


the result of its basic operation.

The operation of insertion and deletion are to be performed based on the


priority means which element can be inserting first and which will be
deleting first is called priority queue.

Take example of Operation system different task can be performed as per


priority but when the interrupt come then it has to serve first because it is
higher priority.

There are to type of priority queue generally used

1. Ascending priority queue


2. Descending priority queue

If the element with the smallest value priority is to be removed first it is


said to ascending priority queue.
If the element with the highest priority is to be removed first it is said to
be descending priority queue.

 Application of Queue:-

main application of the queue is

1. Simulation
2. Time Sharing System

Simulation is used when it would be to expensive or dangerous to


experiment with real system

Ex. wind tunnel used to experiment with design for air body, flight
simulation use to train air pilots, mathematical simulation are set of
equation use to describe some system and computer simulation are step
of program to imitate the behavior of system under study.
When one object in a system is involved in some action and other is
waiting for that then queue is used to manage that.

Ex. one small but very busy airport has only one runway to landing and
takeoff so we have to consider the thing that only no one can land or
takeoff if someone is use the runway so at that time if we put the landing
request in one queue and the takeoff queue for the request of takeoff and
if there is no requests id available for landing then only we can call to the
takeoff plane which has coming first at that time queue concept are very
useful.

You might also like