Unit 2 Stacks and Queues

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 57

UNIT 2

STACKS AND QUEUES

1.Introduction,Stack as ADT
2. Representation and implementation of stack using sequential and
linked allocation
3. Queue as ADT
4. Representation and implementation of Queue using sequential
and linked allocation
5.Circular queue and its implementation
6.Application of stack for expression evaluation
and expression conversion,
7.Recursion, priority queue
Introduction
• A stack is a basic data structure, it’s defined as an ordered collection of
elements represented by a real physical stack.
• Linear data structure features insertion and deletion of items take place at one
end called top of the stack.
• Therefore, In these structure data set as a stack of books or plates, in the
stack, you can remove the item from the top order. you can use these
concepts or structures all throughout programming. the implementation of the
stack also know as LIFO (Last in First Out)
• these are the three basic concepts that can be performed on stacks.
1) push (insert the items into a stack)
2) Pop (delete an item from the stack)
Algorithm for Push and Pop Function

• An algorithm for the Push operation: push (int item) inserts the element to
the top of the stack [max size].
Step 1: Start
Step 2: Initialize
Set top= -1
Step 3: Repeat steps 3 to 5 until top < max size-1
Step 4: Read item.
Step 5: Set top = top +1
Step 6: Set stack [top] = item
Step 7: Otherwise Print “stack is over fow”
Step 8: Stop
An algorithm for the Pop operation: the pop ( ) removes the
element from the top of the stack
• Step 1: Start
• Step 2: Repeat step 3 to 5 until top >= 0
• Step 3: Set item = Stack[top]
• Step 4: Set top = top -1
• Step 5:Print, No deleted is, Item.
• Step 6: Otherwise Print stack under flows.
• Step 7: Stop
Abstract Data Type (ADT)
• A stack contains elements of the same type arranged in sequential order and
push and pop operations occur at one end at the top of the stack. The
following operations may be carried out on the stack:
• Push () – Insert an item on one end of the stack called the top.
• Pop () – Removes and returns the item to the top of the stack, if it is not
• empty.
• Top () – Returns the element to the top of the stack without deleting it,
• if the stack is not empty.
• Size () – Returns the number of items within the stack.
• IsEmpty () – Returns true if it is empty, otherwise returns false.
• IsFull () – Returns true if the stack is full or returns false.
Example of ADT
The Stack Abstract Data Type
• Stacks are the simplest of all data structures, yet they are also among the
most important. They are used in a host of different applications, and as a
tool for many more sophisticated data structures and algorithms. Formally,
a stack is an abstract data type (ADT) such that an instance S supports the
following two methods:
• S.push(e): Add element e to the top of stack S.
• S.pop( ): Remove and return the top element from the stack S; an error
occurs if the stack is empty
• Additionally, let us define the following accessor methods for convenience:
• S.top( ): Return a reference to the top element of stack S, without removing
it; an error occurs if the stack is empty.
• S.is empty( ): Return True if stack S does not contain any elements.
• len(S): Return the number of elements in stack S; in Python, we
implement this with the special method len()… .
• By convention, we assume that a newly created stack is empty, and that
there is no a priori bound on the capacity of the stack. Elements added to
the stack can have arbitrary type
#include <stdio.h> break; }
int stack[10],i,j,choice=0,n,top=-1; case 2: pop();
void push(); break; void pop ()
void pop(); case 3: show(); {
void show(); break; if(top == -1)
void main () case 4: printf("Exiting...."); {
{ break; printf("Underflow");
printf("Enter the number of elements default: printf("Please Enter valid }
in the stack "); choice "); else
scanf("%d",&n); } top = top -1;
printf("*********Stack operations using } }
array*********"); } void show()
printf("\ void push () {
n----------------------------------------------\n"); { for (i=top;i>=0;i--)
while(1) int val; {
{ if (top == n ) printf("%d\n",stack[i]);
printf("Chose one from the below { }
options...\n"); printf("\n Overflow"); if(top == -1)
printf("\n1.Push\n2.Pop\n3.Show\ } {
n4.Exit"); else printf("Stack is empty");
printf("\n Enter your choice \n"); { }
printf("Enter the value?"); }
scanf("%d",&choice); scanf("%d",&val);
switch(choice) top = top +1;
{ stack[top] = val;
case 1: push(); }
Queue:
Defining Queue ADT
• A list with the restriction that insertion can be performed at one end (tail or rear) and
deletion can be performed at other end (front or head).
• FIFO
Operations
1. Enqueue (x) or Push(x) or Insert (x)
2. Dequeue () or Pop() or Remove ()
3. Front ()
4. IsEmpty()
5. IsFull()
All these operations can be performed in constant time or O(1)
Applications of Queue
• Printer shared in a network
• Process scheduling in a processor
• Wait scenario simulation
Queue implementation using Array
int queue_array[MAX];
int rear = - 1;
int front = - 1;
void insert()
{
int add_item;
printf("Inset the element in queue : ");
scanf("%d", &add_item);

if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
{
/*If queue is initially empty */
front = 0;
rear=0;
}
else
{
rear = rear + 1;
}
queue_array[rear] = add_item;
}
} /* End of insert() */
void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */
void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
} /* End of display() */
Stack using Linked List Representation
• Stack Data Structure As we already know, stacks are linear data structures. This
means that their contexts are stored in what looks like a line. An array, too, is a sort
of linear data structure in which you can access any element directly. However, in a
stack, you can only access the element at its top.
• Stack Implementation with Linked Lists
One disadvantage of using an array to implement a stack is the wasted space---
most of the time most of the array is unused. A more elegant and economical
implementation of a stack uses a linked list, which is a data structure that links
together individual data objects as if they were ``links'' in a ``chain'' of data.
• Top of the stack at the tail
Imagine the scenario where the top of the stack is at the end of the linked
list. Since the Stack ADT uses a LIFO manner to retrieve data, in this case,
new objects would have to be added to the end of the linked list, and
retrieved from the end of the linked list too.
Continued…..
• Create a node first and allocate memory to it.
• If the list is empty then the item is to be pushed as the start node of the list.
This includes assigning value to the data part of the node and assign null to
the address part of the node.
• If there are some nodes in the list already, then we have to add the new
element in the beginning of the list (to not violate the property of the stack).
For this purpose, assign the address of the starting element to the address
field of the new node and make the new node, the starting node of the list.
• Time Complexity : o(1)
Continued…..
void push ()
{
int val;
struct node *ptr =(struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("not able to push the element");
}
else
{
printf("Enter the value");
scanf("%d",&val);
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;

}
printf("Item pushed");

}
}
Deleting a node from the stack (POP operation)
Deleting a node from the top of stack is referred to as pop operation. Deleting a
node from the linked list implementation of stack is different from that in the
array implementation. In order to pop an element from the stack, we need to
follow the following steps :
1) Check for the underflow condition: The underflow condition occurs when we
try to pop from an already empty stack. The stack will be empty if the head
pointer of the list points to null.
2) Adjust the head pointer accordingly: In stack, the elements are popped only
from one end, therefore, the value stored in the head pointer must be deleted
and the node must be freed. The next node of the head node now becomes the
head node.
Time Complexity : o(n)
INT POP()
{
ST *TEMP;
INT NO;
TEMP = TOP;
IF(TOP == NULL)
{
PRINTF("STACK IS ALREADY EMPTY");
EXIT(0);
}
ELSE
{
NO = TEMP->NO;
TOP = TOP -> NEXT;
FREE(TEMP);
}

RETURN(NO);
}
Queue using Linked list
• The array implementation can not be used for the large scale applications where
the queues are implemented. One of the alternative of array implementation is
linked list implementation of queue.
• The storage requirement of linked representation of a queue with n elements is
o(n) while the time requirement for operations is o(1).
• In a linked queue, each node of the queue consists of two parts i.e. data part and
the link part. Each element of the queue points to its immediate next element in the
memory.
• In the linked queue, there are two pointers maintained in the memory i.e. front
pointer and rear pointer. The front pointer contains the address of the starting
element of the queue while the rear pointer contains the address of the last element
of the queue.
• Insertion and deletions are performed at rear and front end respectively. If front
and rear both are NULL, it indicates that the queue is empty.
Continued……
The linked representation of queue is shown in the following figure.

The insert operation append the queue by adding an element to the end of the queue. The new element will be
the last element of the queue.

Firstly, allocate the memory for the new node ptr by using the following statement.

Ptr = (struct node *) malloc (sizeof(struct node));


ptr -> data = item;
if(front == NULL)
{
front = ptr;
rear = ptr;
front -> next = NULL;
rear -> next = NULL;
}
Continued…….
In the second case, the queue contains more than one element. The condition
front = NULL becomes false. In this scenario, we need to update the end
pointer rear so that the next pointer of rear will point to the new node ptr. Since,
this is a linked queue, hence we also need to make the rear pointer point to the
newly added node ptr. We also need to make the next pointer of rear point to
NULL.

rear -> next = ptr;


rear = ptr; node1 node 2 (rear)
rear->next = NULL;
void insert(struct node *ptr, int item; )
{

ptr = (struct node *) malloc (sizeof(struct node));


if(ptr == NULL)
{
printf("\nOVERFLOW\n");
return;
}
else
{
ptr -> data = item;
if(front == NULL)
{
front = ptr;
rear = ptr;
front -> next = NULL;
rear -> next = NULL;
}
else
{
rear -> next = ptr;
rear = ptr;
rear->next = NULL;
}
}
Delete Operation :
• Deletion operation removes the element that is first inserted among all the queue elements. Firstly,
we need to check either the list is empty or not. The condition front == NULL becomes true if the list is
empty, in this case , we simply write underflow on the console and make exit.
• Otherwise, we will delete the element that is pointed by the pointer front. For this purpose, copy the
node pointed by the front pointer into the pointer ptr. Now, shift the front pointer, point to its next node
and free the node pointed by the node ptr. This is done by using the following statements.
• Algorithm
• Step 1: IF FRONT = NULL
• Write " Underflow "
• Go to Step 5
• [END OF IF]
• Step 2: SET PTR = FRONT
• Step 3: SET FRONT = FRONT -> NEXT
• Step 4: FREE PTR
• Step 5: END
Delete function of Queue :
• void delete (struct node *ptr)
•{
• if(front == NULL)
• {
• printf("\nUNDERFLOW\n");
• return;
• }
• else
• {
• ptr = front;
• front = front -> next;
• free(ptr);
• }
•}
Applications of Stacks :

• Stacks are used extensively, for storage of values


and return location upon a procedure call.
• We will consider following applications :
❑Expression conversion and evaluation
❑Reverse a string
❑Parsing
Expression conversion and Evaluation :
1) Infix :
In usual algebric notation the operator is in between the two operands, called as “Infix” notation. 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, that’s why the notation is called
infix .
2) Prefix :
The prefix notation in which the operator is written before the operands, it is also called as polish
notation. The expression is look like :
+AB
3) Postfix :
In the postfix notation the operator are written after the operands.it is also known as suffix notation or
reverse polish notation. The postfix expression looks like :
AB+
Why expression evaluation?
• Because the postfix notation is a type of notation which is most suitable for a computer
to calculate any expression (due to its reversing characteristic) and is universally
accepted notation for designing arithmetic and logical unit (ALU) of the CPU. Therefor
it is necessary for us to study the postfix notation.
• While knowing about expression evaluation we must understand what is an expression
in C and what is an expression means. An expression in C is defined as 2 or more
operands are connected by one operator and which can also be said to a formula to
perform any operation. An operand is a function reference, an array element, a
variable, or any constant.
• An operator is symbols like “+”, “-“, “/”, “*” etc. Now expression evaluation is nothing
but operator precedence and associativity. Expression precedence in C tells you which
operator is performed first, next, and so on in an expression with more than one
operator with different precedence.
• If we get 2 same precedences appear in an expression, then it is said to be
“Associativity”. Now in this case we can calculate this statement either from Left to right
or right to left because this both are having the same precedence.
Continued…..
Let an expression A+B*C is given, which is in infix notation. To calculate this expression for
values 4, 3, 7 for A, B, C respectively. We must follow certain rule to have right result. For
example :
A + B *C = 4 + 3 * 7
= 7*7 = 49
is this right result ? No , this is because the multiplication is to be done before addition,
because it has a higher priority over addition.
For an expression to be calculated we must have the knowledge of priority of the operators.
Thus the above expression is interpreted as, A +(B*C)
Operator Precedence:

Exponential Operator ^ Highest Precedence


Multiplication/Division *, / Next Precedence
Addition/Substraction +, - Least Precedence
• Converting infix expression to postfix form :
A+B*C Infix form
A + (B * C) Paranthesized expression
A + (BC *) convert the multiplication
A (BC * ) + convert the addition
ABC *+ postfix Form
Precedence and associativity of operators:
Steps for stack conversion:
• Initialize the Stack.
• Scan the operator from left to right in the infix expression.
• If the leftmost character is an operand, set it as the current output to the Postfix string.
• And if the scanned character is the operator and the Stack is empty or contains the '(', ')'
symbol, push the operator into the Stack.
• If the scanned operator has higher precedence than the existing precedence operator in
the Stack or if the Stack is empty, put it on the Stack.
• If the scanned operator has lower precedence than the existing operator in the Stack,
pop all the Stack operators. After that, push the scanned operator into the Stack.
• If the scanned character is a left bracket '(', push it into the Stack.
• If we encountered right bracket ')', pop the Stack and print all output string character
until '(' is encountered and discard both the bracket.
• Repeat all steps from 2 to 8 until the infix expression is scanned.
• Print the Stack output.
• Pop and output all characters, including the operator, from the Stack until it is not empty.
Expression Evaluation using Stack :
Infix: A+B*C/(E-F)
Step by step output for "" expression

Input String Output Stack Operator Stack


A+B*C/(E-F) A
A+B*C/(E-F) A +
A+B*C/(E-F) AB +
A+B*C/(E-F) AB +*
A+B*C/(E-F) ABC +*
A+B*C/(E-F) ABC* +/
A+B*C/(E-F) ABC* +/(
A+B*C/(E-F) ABC*E +/(
A+B*C/(E-F) ABC*E +/(-
A+B*C/(E-F) ABC*EF +/(-
A+B*C/(E-F) ABC*EF- +/
A+B*C/(E-F) ABC*EF-/+
Circular Queue :
Why was the concept of the circular queue introduced?
• There was one limitation in the array implementation of Queue
• . If the rear reaches to the end position of the Queue then there might be possibility
that some vacant spaces are left in the beginning which cannot be utilized. So, to
overcome such limitations, the concept of the circular queue was introduced.
• As we can see in the above image, the rear is at the last position of the Queue
and front is pointing somewhere rather than the 0th position. In the above array,
there are only two elements and other three positions are empty. The rear is at the
last position of the Queue; if we try to insert the element then it will show that
there are no empty spaces in the Queue. There is one solution to avoid such
wastage of memory space by shifting both the elements at the left and adjust the
front and rear end accordingly. It is not a practically good approach because
shifting all the elements will consume lots of time. The efficient approach to avoid
the wastage of the memory is to use the circular queue data structure.
• What is a Circular Queue?
• A circular queue is similar to a linear queue as it is also based on the FIFO (First
In First Out) principle except that the last position is connected to the first position
in a circular queue that forms a circle. It is also known as a Ring Buffer.
Applications of Circular Queue
• The circular Queue can be used in the following scenarios:
• Memory management: The circular queue provides memory management. As we
have already seen that in linear queue, the memory is not managed very
efficiently. But in case of a circular queue, the memory is managed efficiently by
placing the elements in a location which is unused.
• CPU Scheduling: The operating system also uses the circular queue to insert the
processes and then execute them.
• Traffic system: In a computer-control traffic system, traffic light is one of the best
examples of the circular queue. Each light of traffic light gets ON one by one after
every jinterval of time. Like red light gets ON for one minute then yellow light for
one minute and then green light. After green light, the red light gets ON.
• The steps of enqueue operation are given below:
• First, we will check whether the Queue is full or not.
• Initially the front and rear are set to -1. When we insert the first element in a
Queue, front and rear both are set to 0.
• When we insert a new element, the rear gets incremented, i.e., rear=rear+1.
Scenarios for inserting an element
• There are two scenarios in which queue is not full:
• If rear != max - 1, then rear will be incremented to mod(maxsize) and the new
value will be inserted at the rear end of the queue.
• If front != 0 and rear = max - 1, it means that queue is not full, then set the value
of rear to 0 and insert the new element there.
• There are two cases in which the element cannot be inserted:
• When front ==0 && rear = max-1, which means that front is at the first position of
the Queue and rear is at the last position of the Queue.
• front== rear + 1;
• Algorithm to insert an element in a circular queue
• Step 1: IF (REAR+1)%MAX = FRONT 4+1= 5%5 = 0
Write " OVERFLOW "
Goto step 4
[End OF IF]
• Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE IF REAR = MAX - 1 and FRONT ! = 0 rear=4 and front =2
SET REAR = 0
ELSE
SET REAR = (REAR + 1) % MAX 0+1 = 1%5 =1
[END OF IF]
• Step 3: SET QUEUE[REAR] = VAL
Step 4: EXIT
• Dequeue Operation
• The steps of dequeue operation are given below:
• First, we check whether the Queue is empty or not. If the queue is empty, we cannot perform the
dequeue operation.
• When the element is deleted, the value of front gets decremented by 1.
• If there is only one element left which is to be deleted, then the front and rear are reset to -1.
• Algorithm to delete an element from the circular queue
• Step 1: IF FRONT = -1
Write " UNDERFLOW "
Goto Step 4
[END of IF]
• Step 2: SET VAL = QUEUE[FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]
• Step 4: EXIT
• #include <stdio.h>

• # define max 6
• int queue[max]; // array declaration
• int front=-1;
• int rear=-1;
• // function to insert an element in a circular queue
• void enqueue(int element)
• {
• if(front==-1 && rear==-1) // condition to check queue is empty
• {
• front=0;
• rear=0;
• queue[rear]=element;
• }
• else if((rear+1)%max==front) // condition to check queue is full
• {
• printf("Queue is overflow..");
• }
• else
• {
• rear=(rear+1)%max; // rear is incremented
• queue[rear]=element; // assigning a value to the queue at the rear position.
• }
• }

• // function to delete the element from the queue
• int dequeue()
• {
• if((front==-1) && (rear==-1)) // condition to check queue is empty
• {
• printf("\nQueue is underflow..");
• }
• else if(front==rear)
• {
• printf("\nThe dequeued element is %d", queue[front]);
• front=-1;
• rear=-1;
• }
• else
• {
• printf("\nThe dequeued element is %d", queue[front]);
• front=(front+1)%max;
• }
• }
• // function to display the elements of a queue
• void display()
• {
• int i=front;
• if(front==-1 && rear==-1)
• {
• printf("\n Queue is empty..");
• }
• else
• {
• printf("\nElements in a Queue are :");
• while(i<=rear)
• {
• printf("%d,", queue[i]);
• i=(i+1)%max;
• }
• }
• }
• int main()
• {
• int choice=1,x; // variables declaration

• while(choice<4 && choice!=0) // while loop
• {
• printf("\n Press 1: Insert an element");
• printf("\nPress 2: Delete an element");
• printf("\nPress 3: Display the element");
• printf("\nEnter your choice");
• scanf("%d", &choice);

• switch(choice)
• {

• case 1:

• printf("Enter the element which is to be inserted");
• scanf("%d", &x);
• enqueue(x);
• break;
• case 2:
• dequeue();
• break;
• case 3:
• display();

• }}
• return 0;
• }
Infix to prefix conversion
Iterate the given expression from left to right, one character at a time
Step 1: First reverse the given expression
Step 2: If the scanned character is an operand, put it into prefix expression.
Step 3: If the scanned character is an operator and operator's stack is empty, push operator into
operators' stack.
Step 4: If the operator's stack is not empty, there may be following possibilities.
If the precedence of scanned operator is greater than the top most operator of operator's stack, push this
operator into operator 's stack.
If the precedence of scanned operator is less than the top most operator of operator's stack, pop the
operators from operator's stack untill we find a low precedence operator than the scanned character.
If the precedence of scanned operator is equal then check the associativity of the operator. If associativity
left to right then simply put into stack. If associativity right to left then pop the operators from stack until we
find a low precedence operator.
If the scanned character is opening round bracket ( '(' ), push it into operator's stack.
If the scanned character is closing round bracket ( ')' ), pop out operators from operator's stack until we
find an opening bracket ('(' ).
Repeat Step 2,3 and 4 till expression has character
Step 5: Now pop out all the remaining operators from the operator's stack and push into postfix expression.
Step 6: Exit
• Infix Expression: (A+B)+C-(D-E)^F
• First reverse the given infix expression
• After Reversing: F^)E-D(-C+)B+A(
Input Token Stack Expression Action
F F Add F into expression string
^ ^ F Push ‘^’ into stack
) ^) FE Push ‘)’ into stack
E ^) FE Add E into expression string
– ^)- FE Push ‘-‘ into stack
D ^)- FED Add D into expression string
( ^)- FED- ‘(‘ Pair matched, so pop operator ‘-‘
– – FED-^ ‘-‘ operator has less precedence than ‘^’, so pop ^ and add to expression string
C – FED-^C Add C into expression string
+ + FED-^C- Pop – because – and + have left associativity
) +) FED-^C- Push ‘)’ into stack
B +) FED-^C-B Add B into expression string
+ +)+ FED-^C-B Push ‘+’ into stack
A +)+ FED-^C-BA Add A into expression string
( + FED-^C-BA+ ‘(‘ Pair matched, so pop operator ‘+’
FED-^C-BA++ Pop all operators one by one as we have reached end of the expression
Now reverse the expression to get prefix expression ++AB-C^-DEF
Expression = (A+B^C)*D+E^5
Step 1. Reverse the infix expression.
5^E+D*)C^B+A(
Step 2. Make Every '(' as ')' and every ')' as '('
5^E+D*(C^B+A)
Expression Stack Output Comment
Step 3. Convert expression to postfix form.
5^E+D*(C^B+A
Empty - Initial
)
^E+D*(C^B+A) Empty 5 Print
E+D*(C^B+A) ^ 5 Push
+D*(C^B+A) ^ 5E Push
D*(C^B+A) + 5E^ Pop And Push
*(C^B+A) + 5E^D Print
(C^B+A) +* 5E^D Push
C^B+A) +*( 5E^D Push
^B+A) +*( 5E^DC Print
B+A) +*(^ 5E^DC Push
+A) +*(^ 5E^DCB Print
A) +*(+ 5E^DCB^ Pop And Push
) +*(+ 5E^DCB^A Print
End +* 5E^DCB^A+ Pop Until '('
Pop Every
End Empty 5E^DCB^A+*+
element
Recursion
❑ Recursion is the process which comes into existence when a function calls a
copy of itself to work on a smaller problem. Any function which calls itself is called
recursive function, and such function calls are called recursive calls. Recursion
involves several numbers of recursive calls. However, it is important to impose a
termination condition of recursion. Recursion code is shorter than iterative code
however it is difficult to understand.
❑ Recursion cannot be applied to all the problem, but it is more useful for the tasks
that can be defined in terms of similar subtasks. For Example, recursion may be
applied to sorting, searching, and traversal problems.
❑ Generally, iterative solutions are more efficient than recursion since function call
is always overhead. Any problem that can be solved recursively, can also be solved
iteratively. However, some problems are best suited to be solved by the recursion,
for example, tower of Hanoi, Fibonacci series, factorial finding, etc.
Factorial Program using Recursion
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
Execution of Recursion
Priority Queue :
• A priority queue is a special type of queue in which each element is associated with a priority
value. And, elements are served on the basis of their priority. That is, higher priority elements
are served first.

• However, if elements with the same priority occur, they are served according to their order in
the queue.

• Assigning Priority Value

• Generally, the value of the element itself is considered for assigning the priority. For example,

• The element with the highest value is considered the highest priority element. However, in
other cases, we can assume the element with the lowest value as the highest priority
element.

• We can also set priorities according to our needs.


Difference between Priority Queue and Normal Queue
In a queue, the first-in-first-out rule is implemented whereas, in a priority queue, the values are
removed on the basis of priority. The element with the highest priority is removed first.

Types of Priority Queue:

Min Priority Queue: In min priority Queue minimum number of value gets the highest priority and lowest
number of element gets the highest priority.
Max Priority Queue: Max priority Queue is the opposite of min priority Queue in it maximum number
value gets the highest priority and minimum number of value gets the minimum priority.

Priority Queue Implementation


Priority Queue can be implemented in two ways:
1) Using ordered Array: In ordered array insertion or enqueue operation takes O(n) time complexity
because it enters elements in sorted order in queue. And deletion takes O(1) time complexity.
2) Using unordered Array:In unordered array deletion takes O(n) time complexity because it search for
the element in Queue for the deletion and enqueue takes o(1) time complexity.
Enqueue()
IF((Front == 0)&&(Rear == N-1))
PRINT “Overflow Condition”
Else
IF(Front == -1)
Front = Rear =0
Queue[Rear] = Data
Priority[Rear] = Priority
ELSE IF(Rear ==N-1)
FOR i=Front;i<=Rear;i++)
FOR(i=Front;i<=Rear;i++)
Q[i-Front] =Q[i]
Pr[i-Front] = Pr[i]
Rear = Rear-Front
Front = 0
FOR(i = r;i>f;i–)
IF(p>Pr[i])
Q[i+1] = Q[i] Pr[i+1] = Pr[i]
ELSE
Q[i+1] = data Pr[i+1] = p
Rear++
Dequeue()
IF(Front == -1)
PRINT “Queue Under flow condition”
ELSE
PRINT”Q[f],Pr[f]”
IF(Front==Rear)
Front = Rear = -1
ELSE
FRONT++

Print()
FOR(i=Front;i<=Rear;i++)
PRINT(Q[i],Pr[i])

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy