SlideShare a Scribd company logo
Department of Computer Science (UG)
Data structures
(24BCA2T421)
Stack and Queue
Dr.Poongothai P
Assistant Professor
Department of Computer Science (UG)
Kristu Jayanti College (Autonomous)
Bengaluru.
UNIT – III
STACK and QUEUE
STACK:
 Stack is a linear data structure that follows a particular order in which the
operations are performed.
 The order may be LIFO(Last In First Out) or FILO(First In Last Out).
 LIFO implies that the element that is inserted last, comes out first
and FILO implies that the element that is inserted first, comes out last.
Example:
 Real-world stack, piles of books, etc.
 A Stack is an abstract data type with a pre-defined capacity, which means
that it can store the elements of a limited size.
 It is a data structure that follows some order to insert and delete the
elements, and that order can be LIFO or FILO.
 Consider a plate stacked over one another in the canteen. The plate which is
at the top is the first one to be removed, i.e. the plate which has been
placed at the bottommost position remains in the stack for the longest
period of time.
Working of Stack:
 Stack works on the LIFO pattern.
 Example there are five memory blocks in the stack; therefore, the size of
the stack is 5.
 Suppose we want to store the elements in a stack and let's assume
that stack is empty.
 We have taken the stack of size 5 as shown below in which we are pushing
the elements one by one until the stack becomes full.
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.
 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.
Stack Implementation:
PUSH operation:
The steps involved in the PUSH operation are given below:
 Before inserting an element in a stack, we check whether the stack is full.
 If we try to insert the element in a stack, and the stack is full, then
the overflow condition occurs.
 When we initialize a stack, we set the value of top as -1 to check that
the stack is empty.
 When the new element is pushed in a stack, first, the value of the top gets
incremented, i.e., top=top+1, and the element will be placed at the new
position of the top.
 The elements will be inserted until we reach the max size of the stack.
POP operation:
The steps involved in the POP operation are given below:
 Before deleting the element from the stack, we check whether the stack is
empty.
 If we try to delete the element from the empty stack,
then
the underflow condition occurs.
 If the stack is not empty, we first access the element which is pointed by
the top
 Once the pop operation is performed, the top is decremented by 1,
i.e., top=top-1.
Stack Notations
Following is the various Applications of Stack in Data Structure:
 Evaluation of Arithmetic Expressions
 Backtracking
 Delimiter Checking
 Reverse a Data
 Processing Function Calls
1. Evaluation of Arithmetic Expressions
 An arithmetic expression consists of operands and operators.
 In addition to operands and operators, the arithmetic expression may
also include parenthesis like "left parenthesis" and "right parenthesis".
Example: A + (B - C)
To evaluate the expressions, the precedence rules for the five basic arithmetic
operators are:
Operators Associativity Precedence
^ exponentiation Right to left
Highest followed by *Multiplication
and /division
*Multiplication, /division Left to right
Highest followed by + addition and
– subtraction
+ addition, - subtraction Left to right Lowest
Evaluation of Arithmetic Expression requires two steps:
 First, convert the given expression into special notation.
 Evaluate the expression in this new notation.
Notations for Arithmetic Expression
There are three notations to represent an arithmetic expression:
 Infix Notation
 Prefix Notation
 Postfix Notation
Infix Notation
 The infix notation is an expression in which each operator is placed between
the operands.
 Infix expressions can be parenthesized or unparenthesized depending upon
the problem requirement.
 Example: A + B, (C - D) etc.
 All these expressions are in infix notation because the operator comes
between the operands.
Prefix Notation
 The prefix notation places the operator before the operands and hence often
referred to as polish notation.
 Example: + A B, -CD etc.
 All these expressions are in prefix notation because the operator comes
before the operands.
Postfix Notation
 The postfix notation places the operator after the operands.
 This notation is just the reverse of Polish notation and also known as
Reverse Polish notation.
 Example: AB +, CD+, etc.
 All these expressions are in postfix notation because the operator comes
after the operands.
Conversion of Arithmetic Expression into various Notations:
Infix Notation Prefix Notation Postfix Notation
A * B * A B AB*
(A+B)/C /+ ABC AB+C/
(A*B) + (D-C) +*AB - DC AB*DC-+
Evaluating Postfix expression:
Before evaluating the postfix expression, the following conditions must be
checked. If any one of the conditions fails, the postfix expression is invalid.
 When an operator encounters the scanning process, the Stack must contain a
pair of operands or intermediate results previously calculated.
 When an expression has been completely evaluated, the Stack must contain
exactly one value.
Algorithm for STACK:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5
// Stack structure
typedef struct {
int items[MAX_SIZE];
int top;
} Stack;
// Function to initialize
the stack
void init(Stack *stack) {
stack->top = -1;
}
// Function to check if
the stack is full
int isFull(Stack *stack)
{
return stack->top ==
MAX_SIZE - 1;
}
// Function to check if
the stack is empty
int isEmpty(Stack *stack) {
return stack->top == -1;
}
// Function to push an
element onto the stack
void push(Stack *stack, int value) {
if (isFull(stack)) {
return;
}
stack->top++;
stack->items[stack->top] = value;
printf("Pushed %dn", value);
}
// Function to pop an element
from the stack
int pop(Stack *stack) {
int item;
if (isEmpty(stack))
{ printf("Stack is empty
n");
return -1;
}
item = stack->items[stack->top];
stack->top--;
return item;
}
// Function to peek at the top
element of the stack
int peek(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is emptyn");
return -1;
}
return stack->items[stack-
>top];
}
int main()
{ Stack
stack;
init(&stack);
push(&stack,
1);
push(&stack,
2);
push(&stack,
3);
push(&stack,
4);
push(&stack,
5);
push(&stack,
6); // Stack
is full
printf("Peeked
element:
%dn",
peek(&stack
)); //
Output: 5
printf("Popped element: %dn", pop(&stack)); // Output: 5
printf("Popped element: %dn", pop(&stack)); // Output: 4
return 0;
}
Queue Data Structure
 A Queue Data Structure is used for storing and managing data in a
specific order.
 It follows the principle of “First in, First out” (FIFO), where the first
element added to the queue is the first one to be removed.
 Queues are commonly used in various algorithms and applications for
their simplicity and efficiency in managing data flow.
FIFO Principle of Queue:
 A Queue is like a line waiting to purchase tickets, where the first person in
line is the first person served. (i.e. First come first serve).
 Position of the entry in a queue ready to be served, that is, the first entry that
will be removed from the queue, is called the front of the
queue(sometimes, head of the queue), similarly, the position of the last entry
in the queue, that is, the one most recently added, is called the rear (or
the tail) of the queue.
Characteristics of Queue:
 Queue can handle multiple data.
 We can access both ends.
 They are fast and flexible.
Basic Operations on Queue:
Some of the basic operations for Queue in Data Structure are:
 enqueue() – Insertion of elements to the queue.
 dequeue() – Removal of elements from the queue.
 peek() or front()- Acquires the data element available at the front node of
the queue without deleting it.
 rear() – This operation returns the element at the rear end without removing
it.
 isFull() – Validates if the queue is full.
 isEmpty() – Checks if the queue is empty.
 size(): This operation returns the size of the queue i.e. the total number of
elements it contains.
Operation 1: enqueue()
 Inserts an element at the end of the queue i.e. at the rear end.
The following steps should be taken to enqueue (insert) data into a queue:
o Check if the queue is full.
o If the queue is full, return overflow error and exit.
o If the queue is not full, increment the rear pointer to point to the
next empty space.
o Add the data element to the queue location, where the rear is pointing.
o return success.
// Function to add an item to the queue.
// It changes rear and size
void enqueue(struct Queue* queue, int item)
{
if (isFull(queue))
return;
queue->rear = (queue->rear + 1) % queue->capacity;
queue->array[queue->rear] = item;
queue->size = queue->size + 1;
printf("%d enqueued to queuen", item);
}
Complexity Analysis:
 Time Complexity: O(1)
 Space Complexity: O(N)
Operation 2: dequeue()
This operation removes and returns an element that is at the front end of
the queue.
The following steps are taken to perform the dequeue operation:
 Check if the queue is empty.
 If the queue is empty, return the underflow error and exit.
 If the queue is not empty, access the data where the front is pointing.
 Increment the front pointer to point to the next available data element.
 The Return success.
// Function to remove an item from queue.
// It changes front and size
int dequeue(struct Queue* queue)
{
if (isEmpty(queue)) { printf("
nQueue is emptyn");
return;
}
int item = queue->array[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->size = queue->size - 1;
return item;
}
Complexity Analysis:
 Time Complexity: O(1)
 Space Complexity: O(N)
Operation 3: front()
This operation returns the element at the front end without removing
it. The following steps are taken to perform the front operation:
 If the queue is empty return the most minimum value.
 otherwise, return the front value.
// Function to get front of queue
int front(struct Queue* queue)
{
if (isempty(queue))
return INT_MIN;
return queue->arr[queue->front];
}
Complexity Analysis:
 Time Complexity: O(1)
 Space Complexity: O(N)
Operation 4 : rear()
This operation returns the element at the rear end without removing
it. The following steps are taken to perform the rear operation:
 If the queue is empty return the most minimum value.
 otherwise, return the rear value.
// Function to get rear of queue
int front(struct Queue* queue)
{
if (isempty(queue))
return INT_MIN;
return queue->arr[queue->rear];
}
Complexity Analysis:
 Time Complexity: O(1)
 Space Complexity: O(N)
Operation 5: isEmpty():
This operation returns a boolean value that indicates whether the queue is empty or
not.
The following steps are taken to perform the Empty operation:
 check if front value is equal to -1 or not, if yes then return true means queue
is empty.
 Otherwise return false, means queue is not empty
// Queue is empty when size is 0
bool isEmpty(struct Queue* queue)
{
return (queue->size == 0);
}
Complexity Analysis:
 Time Complexity: O(1)
 Space Complexity: O(N)
Operation 6 : isFull()
This operation returns a boolean value that indicates whether the queue is full or
not.
The following steps are taken to perform the isFull() operation:
 Check if front value is equal to zero and rear is equal to the capacity of
queue if yes then return true.
 otherwise return false
// Queue is full when size becomes equal to the capacity
bool isFull(struct Queue* queue)
{
return (queue->size == queue->capacity);
}
Complexity Analysis:
 Time Complexity: O(1)
 Space Complexity: O(N)
Operation 7: size()
This operation returns the size of the queue i.e. the total number of elements it
contains.
queuename.size()
Parameters : No parameters are passed
Returns : Number of elements in the container
Complexity Analysis:
 Time Complexity: O(1)
 Space Complexity: O(N)
Types of Queue:
There are four different types of queue that are listed as follows -
o Simple Queue or Linear Queue
o Circular Queue
o Priority Queue
o Double Ended Queue (or Deque)
Simple Queue or Linear Queue:
 In Linear Queue, an insertion takes place from one end while the deletion
occurs from another end.
 The end at which the insertion takes place is known as the rear end, and the
end at which the deletion takes place is known as front end.
 It follows the FIFO rule.
 The major drawback of using a linear Queue is that insertion is done only
from the rear end.
 If the first three elements are deleted from the Queue, we cannot insert more
elements even though the space is available in a Linear Queue.
 In this case, the linear Queue shows the overflow condition as the rear is
pointing to the last element of the Queue.
Algorithm for Linear Queue:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5
// Linear Queue
structure
typedef struct {
int items[MAX_SIZE];
int front, rear;
} LinearQueue;
// Function to initialize the linear queue
void init(LinearQueue *queue) {
queue->front = -1;
queue->rear = -1;
}
// Function to check if the queue is full
int isFull(LinearQueue *queue) {
return queue->rear == MAX_SIZE - 1;
}
// Function to check if the queue is empty
int isEmpty(LinearQueue *queue) {
return queue->front == -1;
}
// Function to add an element to the
queue
void enqueue(LinearQueue *queue, int value) {
if (isFull(queue)) {
printf("Queue is fulln");
return;
}
if (isEmpty(queue)) {
queue->front = 0;
}
queue->rear++;
queue->items[queue->rear] = value;
printf("Inserted %dn", value);
}
// Function to remove an element from the queue
int dequeue(LinearQueue *queue) {
int item;
if (isEmpty(queue))
{ printf("Queue is empty
n"); return -1;
}
item = queue->items[queue->front];
if (queue->front == queue->rear) {
queue->front = -1;
queue->rear = -1;
} else {
queue->front++;
}
return item;
}
// Function to display the elements of the queue
void display(LinearQueue *queue) {
if (isEmpty(queue)) {
printf("Queue is emptyn");
return;
}
printf("Front -> ");
for (int i = queue->front; i <= queue->rear; i++) {
printf("%d -> ", queue->items[i]);
}
printf("Rearn");
}
int main() {
LinearQueue queue;
init(&queue);
enqueue(&queue, 1);
enqueue(&queue, 2);
enqueue(&queue, 3);
enqueue(&queue, 4);
enqueue(&queue, 5);
enqueue(&queue, 6); // Queue is full
display(&queue); // Output: 1 -> 2 -> 3 -> 4 -> 5 -> Rear
printf("Deleted element: %dn", dequeue(&queue));
printf("Deleted element: %dn", dequeue(&queue));
display(&queue); // Output: 3 -> 4 -> 5 -> Rear
enqueue(&queue, 6);
display(&queue); // Output: 3 -> 4 -> 5 -> 6 -> Rear
return 0; }
Circular Queue:
 In Circular Queue, all the nodes are represented as circular.
 It is similar to the linear Queue except that the last element of the queue is
connected to the first element.
 It is also known as Ring Buffer, as all the ends are connected to another
end.
 The drawback that occurs in a linear queue is overcome by using the
circular queue.
 If the empty space is available in a circular queue, the new element can
be added in an empty space by simply incrementing the value of rear.
 The main advantage of using the circular queue is better memory
utilization.
Example of Circular Queue:
Data Structures Stack and Queue Data Structures
Data Structures Stack and Queue Data Structures
Data Structures Stack and Queue Data Structures
Algorithm of Circular Queue:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5
// Circular Queue structure
typedef struct {
int items[MAX_SIZE];
int front, rear;
} CircularQueue;
// Function to initialize the circular queue
void init(CircularQueue *queue) {
queue->front = -1;
queue->rear = -1;
}
// Function to check if the queue is full
int isFull(CircularQueue *queue) {
return (queue->front == 0 &&
queue->rear == MAX_SIZE - 1) ||
(queue->rear
== (queue->front - 1) % (MAX_SIZE
- 1));
}
// Function to check if the queue is empty
int isEmpty(CircularQueue *queue) {
return queue->front == -1;
}
// Function to add an element to the
queue
void enqueue(CircularQueue *queue, int value) {
if (isFull(queue)) {
printf("Queue is full
n"); return;
}
if (isEmpty(queue)) {
queue->front = 0;
queue->rear = 0;
} else {
queue->rear =
(queue->rear + 1)
% MAX_SIZE;
}
queue->items[queue->rear] = value;
printf("Inserted %dn", value);
}
// Function to remove an element from the queue
int dequeue(CircularQueue *queue) {
int item;
if (isEmpty(queue))
{ printf("Queue is empty
n"); return -1;
}
if (queue->front == queue-
>rear) {
item = queue->items[queue->front];
queue->front = -1;
queue->rear = -1;
} else {
item = queue->items[queue->front];
queue->front = (queue->front + 1) % MAX_SIZE;
}
return item;
}
// Function to display the elements of the queue
void display(CircularQueue *queue) {
if (isEmpty(queue))
{ printf("Queue is empty
n"); return;
}
printf("Front -> ");
for (int i = queue->front; i != queue->rear; i = (i + 1) % MAX_SIZE) {
printf("%d -> ", queue->items[i]);
}
printf("%d -> Rearn", queue->items[queue->rear]);
}
int main() {
CircularQueue queue;
init(&queue);
enqueue(&queue, 1);
enqueue(&queue, 2);
enqueue(&queue, 3);
enqueue(&queue, 4);
enqueue(&queue, 5);
enqueue(&queue, 6); // Queue is full
display(&queue); // Output: 1 -> 2 -> 3 -> 4 -> 5 -> Rear
printf("Deleted element: %dn", dequeue(&queue));
printf("Deleted element: %dn", dequeue(&queue));
display(&queue); // Output: 3 -> 4 -> 5 -> Rear
enqueue(&queue, 6);
display(&queue); // Output: 3 -> 4 -> 5 -> 6 -> Rear
return 0;
}
Ad

More Related Content

Similar to Data Structures Stack and Queue Data Structures (20)

stacks and queues
stacks and queuesstacks and queues
stacks and queues
DurgaDeviCbit
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparation
RAtna29
 
week 7,8,10,11 alll files included from .ppt
week 7,8,10,11 alll files included from .pptweek 7,8,10,11 alll files included from .ppt
week 7,8,10,11 alll files included from .ppt
LidetAdmassu
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
Pulkitmodi1998
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
pinakspatel
 
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.pptStack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
aamirali1061a
 
Stack data structures with definition and code
Stack data structures with definition and codeStack data structures with definition and code
Stack data structures with definition and code
bansidharj11
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
skilljiolms
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
Yaksh Jethva
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
line24arts
 
Stack and queue
Stack and queueStack and queue
Stack and queue
CHANDAN KUMAR
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
chandankumar364348
 
Stack in Data Structure
Stack in Data StructureStack in Data Structure
Stack in Data Structure
Usha P
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
nikshaikh786
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
KALPANAC20
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
prakashvs7
 
Stack - Operations and Applications
Stack - Operations and ApplicationsStack - Operations and Applications
Stack - Operations and Applications
Sagacious IT Solution
 
Data structure Stack
Data structure StackData structure Stack
Data structure Stack
Praveen Vishwakarma
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
SeethaDinesh
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
SeethaDinesh
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparation
RAtna29
 
week 7,8,10,11 alll files included from .ppt
week 7,8,10,11 alll files included from .pptweek 7,8,10,11 alll files included from .ppt
week 7,8,10,11 alll files included from .ppt
LidetAdmassu
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
Pulkitmodi1998
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
pinakspatel
 
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.pptStack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
Stack ppt file of Stack DSA For lab in the lab of DSA lecture and Lab.ppt
aamirali1061a
 
Stack data structures with definition and code
Stack data structures with definition and codeStack data structures with definition and code
Stack data structures with definition and code
bansidharj11
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
skilljiolms
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
Yaksh Jethva
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
line24arts
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
chandankumar364348
 
Stack in Data Structure
Stack in Data StructureStack in Data Structure
Stack in Data Structure
Usha P
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
nikshaikh786
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
KALPANAC20
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
prakashvs7
 

More from poongothai11 (9)

Unix / Linux Operating System introduction.
Unix / Linux Operating System introduction.Unix / Linux Operating System introduction.
Unix / Linux Operating System introduction.
poongothai11
 
Introduction to Database Management Systems
Introduction to Database Management SystemsIntroduction to Database Management Systems
Introduction to Database Management Systems
poongothai11
 
Open System Interconnection model and its layers.pdf
Open System Interconnection model and its layers.pdfOpen System Interconnection model and its layers.pdf
Open System Interconnection model and its layers.pdf
poongothai11
 
Computer Organization Introduction, Generations of Computer.pptx
Computer Organization Introduction, Generations of Computer.pptxComputer Organization Introduction, Generations of Computer.pptx
Computer Organization Introduction, Generations of Computer.pptx
poongothai11
 
C Programming Language Introduction and C Tokens.pdf
C Programming Language Introduction and C Tokens.pdfC Programming Language Introduction and C Tokens.pdf
C Programming Language Introduction and C Tokens.pdf
poongothai11
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms  in Data StructuresSearching and Sorting Algorithms  in Data Structures
Searching and Sorting Algorithms in Data Structures
poongothai11
 
Thread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using threadThread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using thread
poongothai11
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Introduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptxIntroduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptx
poongothai11
 
Unix / Linux Operating System introduction.
Unix / Linux Operating System introduction.Unix / Linux Operating System introduction.
Unix / Linux Operating System introduction.
poongothai11
 
Introduction to Database Management Systems
Introduction to Database Management SystemsIntroduction to Database Management Systems
Introduction to Database Management Systems
poongothai11
 
Open System Interconnection model and its layers.pdf
Open System Interconnection model and its layers.pdfOpen System Interconnection model and its layers.pdf
Open System Interconnection model and its layers.pdf
poongothai11
 
Computer Organization Introduction, Generations of Computer.pptx
Computer Organization Introduction, Generations of Computer.pptxComputer Organization Introduction, Generations of Computer.pptx
Computer Organization Introduction, Generations of Computer.pptx
poongothai11
 
C Programming Language Introduction and C Tokens.pdf
C Programming Language Introduction and C Tokens.pdfC Programming Language Introduction and C Tokens.pdf
C Programming Language Introduction and C Tokens.pdf
poongothai11
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms  in Data StructuresSearching and Sorting Algorithms  in Data Structures
Searching and Sorting Algorithms in Data Structures
poongothai11
 
Thread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using threadThread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using thread
poongothai11
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Introduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptxIntroduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptx
poongothai11
 
Ad

Recently uploaded (20)

Examining Visual Attention in Gaze-Driven VR Learning: An Eye-Tracking Study ...
Examining Visual Attention in Gaze-Driven VR Learning: An Eye-Tracking Study ...Examining Visual Attention in Gaze-Driven VR Learning: An Eye-Tracking Study ...
Examining Visual Attention in Gaze-Driven VR Learning: An Eye-Tracking Study ...
Yasasi Abeysinghe
 
MITOSIS PRESENTATION FOR BIOLOGY AND HSB.pptx
MITOSIS PRESENTATION FOR BIOLOGY AND HSB.pptxMITOSIS PRESENTATION FOR BIOLOGY AND HSB.pptx
MITOSIS PRESENTATION FOR BIOLOGY AND HSB.pptx
shereneramdon1109
 
habsburg monarchy and the ottoman empire.pptx
habsburg monarchy and the ottoman empire.pptxhabsburg monarchy and the ottoman empire.pptx
habsburg monarchy and the ottoman empire.pptx
milica912572
 
Preclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptxPreclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptx
MahitaLaveti
 
UT BIO ANS 12 SE...........................T-1.pdf
UT BIO ANS 12 SE...........................T-1.pdfUT BIO ANS 12 SE...........................T-1.pdf
UT BIO ANS 12 SE...........................T-1.pdf
srijansardar210308
 
Animal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptxAnimal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptx
MahitaLaveti
 
Hybrid seed production technology of castor and DUS characterization
Hybrid seed production technology of castor and DUS characterizationHybrid seed production technology of castor and DUS characterization
Hybrid seed production technology of castor and DUS characterization
Rajendra Bairwa
 
Physics of heat and radiation by the book
Physics of heat and radiation by the bookPhysics of heat and radiation by the book
Physics of heat and radiation by the book
Mominaakram4
 
Structure formation with primordial black holes: collisional dynamics, binari...
Structure formation with primordial black holes: collisional dynamics, binari...Structure formation with primordial black holes: collisional dynamics, binari...
Structure formation with primordial black holes: collisional dynamics, binari...
Sérgio Sacani
 
Sb- and Sn-based materials in Na-ion batteries
Sb- and Sn-based materials in Na-ion batteriesSb- and Sn-based materials in Na-ion batteries
Sb- and Sn-based materials in Na-ion batteries
MichouRatisou
 
Drug transport model in Advance Biopharmaceutics
Drug transport model in Advance BiopharmaceuticsDrug transport model in Advance Biopharmaceutics
Drug transport model in Advance Biopharmaceutics
RushiBharti
 
Nutritional Management of Heat Stress in broiler and layers
Nutritional Management of Heat Stress in broiler and layersNutritional Management of Heat Stress in broiler and layers
Nutritional Management of Heat Stress in broiler and layers
Bihar Veterinary College, Bihar Animal Sciences University, Patna, Bihar, India
 
NORMAL DEVELOPMENT.pptx by the book having complete understanding
NORMAL DEVELOPMENT.pptx by the book having complete understandingNORMAL DEVELOPMENT.pptx by the book having complete understanding
NORMAL DEVELOPMENT.pptx by the book having complete understanding
Mominaakram4
 
Skin_structure_dermis_epidermis_layers of skin
Skin_structure_dermis_epidermis_layers of skinSkin_structure_dermis_epidermis_layers of skin
Skin_structure_dermis_epidermis_layers of skin
muralinath2
 
Health Major for College_ Mendel and Genetic Inheritance by Slidesgo.pptx
Health Major for College_ Mendel and Genetic Inheritance by Slidesgo.pptxHealth Major for College_ Mendel and Genetic Inheritance by Slidesgo.pptx
Health Major for College_ Mendel and Genetic Inheritance by Slidesgo.pptx
dayaneanjos5
 
Adamson, Walter L. - Avant-Garde Florence. From Modernism to Fascism [ocr] [...
Adamson, Walter L.  - Avant-Garde Florence. From Modernism to Fascism [ocr] [...Adamson, Walter L.  - Avant-Garde Florence. From Modernism to Fascism [ocr] [...
Adamson, Walter L. - Avant-Garde Florence. From Modernism to Fascism [ocr] [...
Francisco Sandoval Martínez
 
SEXUAL REPRODUCTION IN FLOWERING PLANTS.pptx
SEXUAL REPRODUCTION IN FLOWERING PLANTS.pptxSEXUAL REPRODUCTION IN FLOWERING PLANTS.pptx
SEXUAL REPRODUCTION IN FLOWERING PLANTS.pptx
dhruti94
 
Astrobiological implications of the stability andreactivity of peptide nuclei...
Astrobiological implications of the stability andreactivity of peptide nuclei...Astrobiological implications of the stability andreactivity of peptide nuclei...
Astrobiological implications of the stability andreactivity of peptide nuclei...
Sérgio Sacani
 
Fire Prevention and protection 1123.pptx
Fire Prevention and protection 1123.pptxFire Prevention and protection 1123.pptx
Fire Prevention and protection 1123.pptx
091HarshikaModi
 
Keynote presentation at DeepTest Workshop 2025
Keynote presentation at DeepTest Workshop 2025Keynote presentation at DeepTest Workshop 2025
Keynote presentation at DeepTest Workshop 2025
Shiva Nejati
 
Examining Visual Attention in Gaze-Driven VR Learning: An Eye-Tracking Study ...
Examining Visual Attention in Gaze-Driven VR Learning: An Eye-Tracking Study ...Examining Visual Attention in Gaze-Driven VR Learning: An Eye-Tracking Study ...
Examining Visual Attention in Gaze-Driven VR Learning: An Eye-Tracking Study ...
Yasasi Abeysinghe
 
MITOSIS PRESENTATION FOR BIOLOGY AND HSB.pptx
MITOSIS PRESENTATION FOR BIOLOGY AND HSB.pptxMITOSIS PRESENTATION FOR BIOLOGY AND HSB.pptx
MITOSIS PRESENTATION FOR BIOLOGY AND HSB.pptx
shereneramdon1109
 
habsburg monarchy and the ottoman empire.pptx
habsburg monarchy and the ottoman empire.pptxhabsburg monarchy and the ottoman empire.pptx
habsburg monarchy and the ottoman empire.pptx
milica912572
 
Preclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptxPreclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptx
MahitaLaveti
 
UT BIO ANS 12 SE...........................T-1.pdf
UT BIO ANS 12 SE...........................T-1.pdfUT BIO ANS 12 SE...........................T-1.pdf
UT BIO ANS 12 SE...........................T-1.pdf
srijansardar210308
 
Animal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptxAnimal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptx
MahitaLaveti
 
Hybrid seed production technology of castor and DUS characterization
Hybrid seed production technology of castor and DUS characterizationHybrid seed production technology of castor and DUS characterization
Hybrid seed production technology of castor and DUS characterization
Rajendra Bairwa
 
Physics of heat and radiation by the book
Physics of heat and radiation by the bookPhysics of heat and radiation by the book
Physics of heat and radiation by the book
Mominaakram4
 
Structure formation with primordial black holes: collisional dynamics, binari...
Structure formation with primordial black holes: collisional dynamics, binari...Structure formation with primordial black holes: collisional dynamics, binari...
Structure formation with primordial black holes: collisional dynamics, binari...
Sérgio Sacani
 
Sb- and Sn-based materials in Na-ion batteries
Sb- and Sn-based materials in Na-ion batteriesSb- and Sn-based materials in Na-ion batteries
Sb- and Sn-based materials in Na-ion batteries
MichouRatisou
 
Drug transport model in Advance Biopharmaceutics
Drug transport model in Advance BiopharmaceuticsDrug transport model in Advance Biopharmaceutics
Drug transport model in Advance Biopharmaceutics
RushiBharti
 
NORMAL DEVELOPMENT.pptx by the book having complete understanding
NORMAL DEVELOPMENT.pptx by the book having complete understandingNORMAL DEVELOPMENT.pptx by the book having complete understanding
NORMAL DEVELOPMENT.pptx by the book having complete understanding
Mominaakram4
 
Skin_structure_dermis_epidermis_layers of skin
Skin_structure_dermis_epidermis_layers of skinSkin_structure_dermis_epidermis_layers of skin
Skin_structure_dermis_epidermis_layers of skin
muralinath2
 
Health Major for College_ Mendel and Genetic Inheritance by Slidesgo.pptx
Health Major for College_ Mendel and Genetic Inheritance by Slidesgo.pptxHealth Major for College_ Mendel and Genetic Inheritance by Slidesgo.pptx
Health Major for College_ Mendel and Genetic Inheritance by Slidesgo.pptx
dayaneanjos5
 
Adamson, Walter L. - Avant-Garde Florence. From Modernism to Fascism [ocr] [...
Adamson, Walter L.  - Avant-Garde Florence. From Modernism to Fascism [ocr] [...Adamson, Walter L.  - Avant-Garde Florence. From Modernism to Fascism [ocr] [...
Adamson, Walter L. - Avant-Garde Florence. From Modernism to Fascism [ocr] [...
Francisco Sandoval Martínez
 
SEXUAL REPRODUCTION IN FLOWERING PLANTS.pptx
SEXUAL REPRODUCTION IN FLOWERING PLANTS.pptxSEXUAL REPRODUCTION IN FLOWERING PLANTS.pptx
SEXUAL REPRODUCTION IN FLOWERING PLANTS.pptx
dhruti94
 
Astrobiological implications of the stability andreactivity of peptide nuclei...
Astrobiological implications of the stability andreactivity of peptide nuclei...Astrobiological implications of the stability andreactivity of peptide nuclei...
Astrobiological implications of the stability andreactivity of peptide nuclei...
Sérgio Sacani
 
Fire Prevention and protection 1123.pptx
Fire Prevention and protection 1123.pptxFire Prevention and protection 1123.pptx
Fire Prevention and protection 1123.pptx
091HarshikaModi
 
Keynote presentation at DeepTest Workshop 2025
Keynote presentation at DeepTest Workshop 2025Keynote presentation at DeepTest Workshop 2025
Keynote presentation at DeepTest Workshop 2025
Shiva Nejati
 
Ad

Data Structures Stack and Queue Data Structures

  • 1. Department of Computer Science (UG) Data structures (24BCA2T421) Stack and Queue Dr.Poongothai P Assistant Professor Department of Computer Science (UG) Kristu Jayanti College (Autonomous) Bengaluru.
  • 2. UNIT – III STACK and QUEUE STACK:  Stack is a linear data structure that follows a particular order in which the operations are performed.  The order may be LIFO(Last In First Out) or FILO(First In Last Out).  LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first, comes out last. Example:  Real-world stack, piles of books, etc.  A Stack is an abstract data type with a pre-defined capacity, which means that it can store the elements of a limited size.  It is a data structure that follows some order to insert and delete the elements, and that order can be LIFO or FILO.  Consider a plate stacked over one another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time.
  • 3. Working of Stack:  Stack works on the LIFO pattern.  Example there are five memory blocks in the stack; therefore, the size of the stack is 5.  Suppose we want to store the elements in a stack and let's assume that stack is empty.  We have taken the stack of size 5 as shown below in which we are pushing the elements one by one until the stack becomes full. 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.
  • 4.  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. Stack Implementation: PUSH operation: The steps involved in the PUSH operation are given below:  Before inserting an element in a stack, we check whether the stack is full.  If we try to insert the element in a stack, and the stack is full, then the overflow condition occurs.  When we initialize a stack, we set the value of top as -1 to check that the stack is empty.  When the new element is pushed in a stack, first, the value of the top gets incremented, i.e., top=top+1, and the element will be placed at the new position of the top.  The elements will be inserted until we reach the max size of the stack.
  • 5. POP operation: The steps involved in the POP operation are given below:  Before deleting the element from the stack, we check whether the stack is empty.  If we try to delete the element from the empty stack, then the underflow condition occurs.  If the stack is not empty, we first access the element which is pointed by the top  Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
  • 6. Stack Notations Following is the various Applications of Stack in Data Structure:  Evaluation of Arithmetic Expressions  Backtracking  Delimiter Checking  Reverse a Data  Processing Function Calls 1. Evaluation of Arithmetic Expressions  An arithmetic expression consists of operands and operators.  In addition to operands and operators, the arithmetic expression may also include parenthesis like "left parenthesis" and "right parenthesis".
  • 7. Example: A + (B - C) To evaluate the expressions, the precedence rules for the five basic arithmetic operators are: Operators Associativity Precedence ^ exponentiation Right to left Highest followed by *Multiplication and /division *Multiplication, /division Left to right Highest followed by + addition and – subtraction + addition, - subtraction Left to right Lowest Evaluation of Arithmetic Expression requires two steps:  First, convert the given expression into special notation.  Evaluate the expression in this new notation. Notations for Arithmetic Expression There are three notations to represent an arithmetic expression:  Infix Notation  Prefix Notation  Postfix Notation Infix Notation  The infix notation is an expression in which each operator is placed between the operands.  Infix expressions can be parenthesized or unparenthesized depending upon the problem requirement.
  • 8.  Example: A + B, (C - D) etc.  All these expressions are in infix notation because the operator comes between the operands. Prefix Notation  The prefix notation places the operator before the operands and hence often referred to as polish notation.  Example: + A B, -CD etc.  All these expressions are in prefix notation because the operator comes before the operands. Postfix Notation  The postfix notation places the operator after the operands.  This notation is just the reverse of Polish notation and also known as Reverse Polish notation.  Example: AB +, CD+, etc.  All these expressions are in postfix notation because the operator comes after the operands. Conversion of Arithmetic Expression into various Notations: Infix Notation Prefix Notation Postfix Notation A * B * A B AB* (A+B)/C /+ ABC AB+C/ (A*B) + (D-C) +*AB - DC AB*DC-+
  • 9. Evaluating Postfix expression: Before evaluating the postfix expression, the following conditions must be checked. If any one of the conditions fails, the postfix expression is invalid.  When an operator encounters the scanning process, the Stack must contain a pair of operands or intermediate results previously calculated.  When an expression has been completely evaluated, the Stack must contain exactly one value.
  • 10. Algorithm for STACK: #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 5 // Stack structure typedef struct { int items[MAX_SIZE]; int top; } Stack; // Function to initialize the stack void init(Stack *stack) { stack->top = -1; } // Function to check if the stack is full int isFull(Stack *stack) { return stack->top == MAX_SIZE - 1; } // Function to check if the stack is empty int isEmpty(Stack *stack) { return stack->top == -1; } // Function to push an element onto the stack void push(Stack *stack, int value) { if (isFull(stack)) {
  • 11. return; } stack->top++; stack->items[stack->top] = value; printf("Pushed %dn", value); } // Function to pop an element from the stack int pop(Stack *stack) { int item; if (isEmpty(stack)) { printf("Stack is empty n"); return -1; } item = stack->items[stack->top]; stack->top--; return item; } // Function to peek at the top element of the stack int peek(Stack *stack) { if (isEmpty(stack)) { printf("Stack is emptyn"); return -1; } return stack->items[stack- >top]; }
  • 12. int main() { Stack stack; init(&stack); push(&stack, 1); push(&stack, 2); push(&stack, 3); push(&stack, 4); push(&stack, 5); push(&stack, 6); // Stack is full printf("Peeked element: %dn", peek(&stack )); // Output: 5 printf("Popped element: %dn", pop(&stack)); // Output: 5 printf("Popped element: %dn", pop(&stack)); // Output: 4 return 0; }
  • 13. Queue Data Structure  A Queue Data Structure is used for storing and managing data in a specific order.  It follows the principle of “First in, First out” (FIFO), where the first element added to the queue is the first one to be removed.  Queues are commonly used in various algorithms and applications for their simplicity and efficiency in managing data flow. FIFO Principle of Queue:  A Queue is like a line waiting to purchase tickets, where the first person in line is the first person served. (i.e. First come first serve).  Position of the entry in a queue ready to be served, that is, the first entry that will be removed from the queue, is called the front of the queue(sometimes, head of the queue), similarly, the position of the last entry in the queue, that is, the one most recently added, is called the rear (or the tail) of the queue.
  • 14. Characteristics of Queue:  Queue can handle multiple data.  We can access both ends.  They are fast and flexible. Basic Operations on Queue: Some of the basic operations for Queue in Data Structure are:  enqueue() – Insertion of elements to the queue.  dequeue() – Removal of elements from the queue.  peek() or front()- Acquires the data element available at the front node of the queue without deleting it.  rear() – This operation returns the element at the rear end without removing it.  isFull() – Validates if the queue is full.  isEmpty() – Checks if the queue is empty.  size(): This operation returns the size of the queue i.e. the total number of elements it contains.
  • 15. Operation 1: enqueue()  Inserts an element at the end of the queue i.e. at the rear end. The following steps should be taken to enqueue (insert) data into a queue: o Check if the queue is full. o If the queue is full, return overflow error and exit. o If the queue is not full, increment the rear pointer to point to the next empty space. o Add the data element to the queue location, where the rear is pointing. o return success.
  • 16. // Function to add an item to the queue. // It changes rear and size void enqueue(struct Queue* queue, int item) { if (isFull(queue)) return; queue->rear = (queue->rear + 1) % queue->capacity; queue->array[queue->rear] = item; queue->size = queue->size + 1; printf("%d enqueued to queuen", item); }
  • 17. Complexity Analysis:  Time Complexity: O(1)  Space Complexity: O(N) Operation 2: dequeue() This operation removes and returns an element that is at the front end of the queue. The following steps are taken to perform the dequeue operation:  Check if the queue is empty.  If the queue is empty, return the underflow error and exit.  If the queue is not empty, access the data where the front is pointing.  Increment the front pointer to point to the next available data element.  The Return success.
  • 18. // Function to remove an item from queue. // It changes front and size int dequeue(struct Queue* queue) { if (isEmpty(queue)) { printf(" nQueue is emptyn"); return; } int item = queue->array[queue->front]; queue->front = (queue->front + 1) % queue->capacity; queue->size = queue->size - 1; return item; } Complexity Analysis:  Time Complexity: O(1)  Space Complexity: O(N) Operation 3: front() This operation returns the element at the front end without removing it. The following steps are taken to perform the front operation:  If the queue is empty return the most minimum value.  otherwise, return the front value. // Function to get front of queue
  • 19. int front(struct Queue* queue) { if (isempty(queue)) return INT_MIN; return queue->arr[queue->front]; } Complexity Analysis:  Time Complexity: O(1)  Space Complexity: O(N) Operation 4 : rear() This operation returns the element at the rear end without removing it. The following steps are taken to perform the rear operation:  If the queue is empty return the most minimum value.  otherwise, return the rear value. // Function to get rear of queue int front(struct Queue* queue) { if (isempty(queue)) return INT_MIN; return queue->arr[queue->rear]; } Complexity Analysis:
  • 20.  Time Complexity: O(1)  Space Complexity: O(N) Operation 5: isEmpty(): This operation returns a boolean value that indicates whether the queue is empty or not. The following steps are taken to perform the Empty operation:  check if front value is equal to -1 or not, if yes then return true means queue is empty.  Otherwise return false, means queue is not empty // Queue is empty when size is 0 bool isEmpty(struct Queue* queue) { return (queue->size == 0); } Complexity Analysis:  Time Complexity: O(1)  Space Complexity: O(N) Operation 6 : isFull() This operation returns a boolean value that indicates whether the queue is full or not. The following steps are taken to perform the isFull() operation:  Check if front value is equal to zero and rear is equal to the capacity of queue if yes then return true.  otherwise return false
  • 21. // Queue is full when size becomes equal to the capacity bool isFull(struct Queue* queue) { return (queue->size == queue->capacity); } Complexity Analysis:  Time Complexity: O(1)  Space Complexity: O(N) Operation 7: size() This operation returns the size of the queue i.e. the total number of elements it contains. queuename.size() Parameters : No parameters are passed Returns : Number of elements in the container Complexity Analysis:  Time Complexity: O(1)  Space Complexity: O(N)
  • 22. Types of Queue: There are four different types of queue that are listed as follows - o Simple Queue or Linear Queue o Circular Queue o Priority Queue o Double Ended Queue (or Deque) Simple Queue or Linear Queue:  In Linear Queue, an insertion takes place from one end while the deletion occurs from another end.  The end at which the insertion takes place is known as the rear end, and the end at which the deletion takes place is known as front end.  It follows the FIFO rule.
  • 23.  The major drawback of using a linear Queue is that insertion is done only from the rear end.  If the first three elements are deleted from the Queue, we cannot insert more elements even though the space is available in a Linear Queue.  In this case, the linear Queue shows the overflow condition as the rear is pointing to the last element of the Queue. Algorithm for Linear Queue: #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 5 // Linear Queue structure typedef struct { int items[MAX_SIZE]; int front, rear; } LinearQueue; // Function to initialize the linear queue void init(LinearQueue *queue) { queue->front = -1; queue->rear = -1; } // Function to check if the queue is full int isFull(LinearQueue *queue) {
  • 24. return queue->rear == MAX_SIZE - 1; } // Function to check if the queue is empty int isEmpty(LinearQueue *queue) { return queue->front == -1; } // Function to add an element to the queue void enqueue(LinearQueue *queue, int value) { if (isFull(queue)) { printf("Queue is fulln"); return; } if (isEmpty(queue)) { queue->front = 0; } queue->rear++; queue->items[queue->rear] = value; printf("Inserted %dn", value); } // Function to remove an element from the queue int dequeue(LinearQueue *queue) {
  • 25. int item; if (isEmpty(queue)) { printf("Queue is empty n"); return -1; } item = queue->items[queue->front]; if (queue->front == queue->rear) { queue->front = -1; queue->rear = -1; } else { queue->front++; } return item; } // Function to display the elements of the queue void display(LinearQueue *queue) { if (isEmpty(queue)) { printf("Queue is emptyn"); return; } printf("Front -> ");
  • 26. for (int i = queue->front; i <= queue->rear; i++) { printf("%d -> ", queue->items[i]); } printf("Rearn"); } int main() { LinearQueue queue; init(&queue); enqueue(&queue, 1); enqueue(&queue, 2); enqueue(&queue, 3); enqueue(&queue, 4); enqueue(&queue, 5); enqueue(&queue, 6); // Queue is full display(&queue); // Output: 1 -> 2 -> 3 -> 4 -> 5 -> Rear printf("Deleted element: %dn", dequeue(&queue)); printf("Deleted element: %dn", dequeue(&queue)); display(&queue); // Output: 3 -> 4 -> 5 -> Rear enqueue(&queue, 6); display(&queue); // Output: 3 -> 4 -> 5 -> 6 -> Rear return 0; }
  • 27. Circular Queue:  In Circular Queue, all the nodes are represented as circular.  It is similar to the linear Queue except that the last element of the queue is connected to the first element.  It is also known as Ring Buffer, as all the ends are connected to another end.  The drawback that occurs in a linear queue is overcome by using the circular queue.  If the empty space is available in a circular queue, the new element can be added in an empty space by simply incrementing the value of rear.  The main advantage of using the circular queue is better memory utilization. Example of Circular Queue:
  • 31. Algorithm of Circular Queue: #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 5 // Circular Queue structure typedef struct { int items[MAX_SIZE]; int front, rear; } CircularQueue; // Function to initialize the circular queue void init(CircularQueue *queue) { queue->front = -1; queue->rear = -1; } // Function to check if the queue is full int isFull(CircularQueue *queue) { return (queue->front == 0 && queue->rear == MAX_SIZE - 1) || (queue->rear == (queue->front - 1) % (MAX_SIZE - 1)); } // Function to check if the queue is empty int isEmpty(CircularQueue *queue) { return queue->front == -1; } // Function to add an element to the queue void enqueue(CircularQueue *queue, int value) { if (isFull(queue)) {
  • 32. printf("Queue is full n"); return; } if (isEmpty(queue)) { queue->front = 0; queue->rear = 0; } else { queue->rear = (queue->rear + 1) % MAX_SIZE; } queue->items[queue->rear] = value; printf("Inserted %dn", value); } // Function to remove an element from the queue int dequeue(CircularQueue *queue) { int item; if (isEmpty(queue)) { printf("Queue is empty n"); return -1; } if (queue->front == queue- >rear) { item = queue->items[queue->front]; queue->front = -1; queue->rear = -1; } else { item = queue->items[queue->front];
  • 33. queue->front = (queue->front + 1) % MAX_SIZE; } return item; } // Function to display the elements of the queue void display(CircularQueue *queue) { if (isEmpty(queue)) { printf("Queue is empty n"); return; } printf("Front -> "); for (int i = queue->front; i != queue->rear; i = (i + 1) % MAX_SIZE) { printf("%d -> ", queue->items[i]); } printf("%d -> Rearn", queue->items[queue->rear]); } int main() { CircularQueue queue; init(&queue); enqueue(&queue, 1); enqueue(&queue, 2); enqueue(&queue, 3); enqueue(&queue, 4); enqueue(&queue, 5); enqueue(&queue, 6); // Queue is full
  • 34. display(&queue); // Output: 1 -> 2 -> 3 -> 4 -> 5 -> Rear printf("Deleted element: %dn", dequeue(&queue)); printf("Deleted element: %dn", dequeue(&queue)); display(&queue); // Output: 3 -> 4 -> 5 -> Rear enqueue(&queue, 6); display(&queue); // Output: 3 -> 4 -> 5 -> 6 -> Rear return 0; }