SlideShare a Scribd company logo
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.
POPoperation:
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)) {
printf("Stack is fulln");
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 emptyn");
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 emptyn");
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:
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 fulln");
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 emptyn");
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 emptyn");
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;
}

More Related Content

Similar to Stack and its operations, Queue and its operations

Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
line24arts
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
prakashvs7
 
CH4.pptx
CH4.pptxCH4.pptx
CH4.pptx
AliJama14
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
nikshaikh786
 
Stack in Data Structure
Stack in Data StructureStack in Data Structure
Stack in Data Structure
UshaP15
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
pinakspatel
 
Stack
StackStack
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
chandankumar364348
 
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
 
5.-Stacks.pptx
5.-Stacks.pptx5.-Stacks.pptx
5.-Stacks.pptx
iloveyoucarlo0923
 
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
 
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
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
skilljiolms
 
Stack
StackStack
Stacks-and-Queues.pdf
Stacks-and-Queues.pdfStacks-and-Queues.pdf
Stacks-and-Queues.pdf
TobyWtf
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
Yaksh Jethva
 
ADT STACK and Queues
ADT STACK and QueuesADT STACK and Queues
ADT STACK and Queues
BHARATH KUMAR
 
Stack data structure
Stack data structureStack data structure
Stack data structure
rogineojerio020496
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
tameemyousaf
 

Similar to Stack and its operations, Queue and its operations (20)

Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
 
CH4.pptx
CH4.pptxCH4.pptx
CH4.pptx
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Stack in Data Structure
Stack in Data StructureStack in Data Structure
Stack in Data Structure
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Stack
StackStack
Stack
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
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
 
5.-Stacks.pptx
5.-Stacks.pptx5.-Stacks.pptx
5.-Stacks.pptx
 
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
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
 
Stack
StackStack
Stack
 
Stacks-and-Queues.pdf
Stacks-and-Queues.pdfStacks-and-Queues.pdf
Stacks-and-Queues.pdf
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
 
ADT STACK and Queues
ADT STACK and QueuesADT STACK and Queues
ADT STACK and Queues
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 

Recently uploaded

All Of My Java Codes With A Sample Output.docx
All Of My Java Codes With A Sample Output.docxAll Of My Java Codes With A Sample Output.docx
All Of My Java Codes With A Sample Output.docx
adhitya5119
 
A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024
Bruce Bennett
 
thyroid case presentation.pptx Kamala's Lakshaman palatial
thyroid case presentation.pptx Kamala's Lakshaman palatialthyroid case presentation.pptx Kamala's Lakshaman palatial
thyroid case presentation.pptx Kamala's Lakshaman palatial
Aditya Raghav
 
Tape Measure Training & Practice Assessments.pdf
Tape Measure Training & Practice Assessments.pdfTape Measure Training & Practice Assessments.pdf
Tape Measure Training & Practice Assessments.pdf
KateRobinson68
 
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
NWEXAM
 
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
2zjra9bn
 
Gabrielle M. A. Sinaga Portfolio, Film Student (2024)
Gabrielle M. A. Sinaga Portfolio, Film Student (2024)Gabrielle M. A. Sinaga Portfolio, Film Student (2024)
Gabrielle M. A. Sinaga Portfolio, Film Student (2024)
GabrielleSinaga
 
IT Career Hacks Navigate the Tech Jungle with a Roadmap
IT Career Hacks Navigate the Tech Jungle with a RoadmapIT Career Hacks Navigate the Tech Jungle with a Roadmap
IT Career Hacks Navigate the Tech Jungle with a Roadmap
Base Camp
 
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAANBUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
cahgading001
 
0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf
Thomas GIRARD BDes
 
Learnings from Successful Jobs Searchers
Learnings from Successful Jobs SearchersLearnings from Successful Jobs Searchers
Learnings from Successful Jobs Searchers
Bruce Bennett
 
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
2zjra9bn
 
Leave-rules.ppt CCS leave rules 1972 for central govt employees
Leave-rules.ppt CCS leave rules 1972 for central govt employeesLeave-rules.ppt CCS leave rules 1972 for central govt employees
Leave-rules.ppt CCS leave rules 1972 for central govt employees
Sreenivas702647
 
Leadership Ambassador club Adventist module
Leadership Ambassador club Adventist moduleLeadership Ambassador club Adventist module
Leadership Ambassador club Adventist module
kakomaeric00
 
Switching Careers Slides - JoyceMSullivan SocMediaFin - 2024Jun11.pdf
Switching Careers Slides - JoyceMSullivan SocMediaFin -  2024Jun11.pdfSwitching Careers Slides - JoyceMSullivan SocMediaFin -  2024Jun11.pdf
Switching Careers Slides - JoyceMSullivan SocMediaFin - 2024Jun11.pdf
SocMediaFin - Joyce Sullivan
 
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
taqyea
 
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
dsnow9802
 
Lbs last rank 2023 9988kr47h4744j445.pdf
Lbs last rank 2023 9988kr47h4744j445.pdfLbs last rank 2023 9988kr47h4744j445.pdf
Lbs last rank 2023 9988kr47h4744j445.pdf
ashiquepa3
 
Connect to Grow: The power of building networks
Connect to Grow: The power of building networksConnect to Grow: The power of building networks
Connect to Grow: The power of building networks
Eirini SYKA-LERIOTI
 

Recently uploaded (19)

All Of My Java Codes With A Sample Output.docx
All Of My Java Codes With A Sample Output.docxAll Of My Java Codes With A Sample Output.docx
All Of My Java Codes With A Sample Output.docx
 
A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024
 
thyroid case presentation.pptx Kamala's Lakshaman palatial
thyroid case presentation.pptx Kamala's Lakshaman palatialthyroid case presentation.pptx Kamala's Lakshaman palatial
thyroid case presentation.pptx Kamala's Lakshaman palatial
 
Tape Measure Training & Practice Assessments.pdf
Tape Measure Training & Practice Assessments.pdfTape Measure Training & Practice Assessments.pdf
Tape Measure Training & Practice Assessments.pdf
 
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
How to Prepare for Fortinet FCP_FAC_AD-6.5 Certification?
 
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
 
Gabrielle M. A. Sinaga Portfolio, Film Student (2024)
Gabrielle M. A. Sinaga Portfolio, Film Student (2024)Gabrielle M. A. Sinaga Portfolio, Film Student (2024)
Gabrielle M. A. Sinaga Portfolio, Film Student (2024)
 
IT Career Hacks Navigate the Tech Jungle with a Roadmap
IT Career Hacks Navigate the Tech Jungle with a RoadmapIT Career Hacks Navigate the Tech Jungle with a Roadmap
IT Career Hacks Navigate the Tech Jungle with a Roadmap
 
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAANBUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
BUKU PENJAGAAN BUKU PENJAGAAN BUKU PENJAGAAN
 
0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf
 
Learnings from Successful Jobs Searchers
Learnings from Successful Jobs SearchersLearnings from Successful Jobs Searchers
Learnings from Successful Jobs Searchers
 
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
 
Leave-rules.ppt CCS leave rules 1972 for central govt employees
Leave-rules.ppt CCS leave rules 1972 for central govt employeesLeave-rules.ppt CCS leave rules 1972 for central govt employees
Leave-rules.ppt CCS leave rules 1972 for central govt employees
 
Leadership Ambassador club Adventist module
Leadership Ambassador club Adventist moduleLeadership Ambassador club Adventist module
Leadership Ambassador club Adventist module
 
Switching Careers Slides - JoyceMSullivan SocMediaFin - 2024Jun11.pdf
Switching Careers Slides - JoyceMSullivan SocMediaFin -  2024Jun11.pdfSwitching Careers Slides - JoyceMSullivan SocMediaFin -  2024Jun11.pdf
Switching Careers Slides - JoyceMSullivan SocMediaFin - 2024Jun11.pdf
 
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
 
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
 
Lbs last rank 2023 9988kr47h4744j445.pdf
Lbs last rank 2023 9988kr47h4744j445.pdfLbs last rank 2023 9988kr47h4744j445.pdf
Lbs last rank 2023 9988kr47h4744j445.pdf
 
Connect to Grow: The power of building networks
Connect to Grow: The power of building networksConnect to Grow: The power of building networks
Connect to Grow: The power of building networks
 

Stack and its operations, Queue and its operations

  • 1. 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.
  • 2. 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.
  • 3.  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.
  • 4. POPoperation: 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.
  • 5. 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".
  • 6. 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.
  • 7.  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-+
  • 8. 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.
  • 9. 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)) { printf("Stack is fulln");
  • 10. 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 emptyn"); 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]; }
  • 11. 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; }
  • 12. 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.
  • 13. 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.
  • 14. 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.
  • 15. // 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); }
  • 16. 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.
  • 17. // 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
  • 18. 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:
  • 19.  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
  • 20. // 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)
  • 21. 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.
  • 22.  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) {
  • 23. 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) {
  • 24. int item; if (isEmpty(queue)) { printf("Queue is emptyn"); 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 -> ");
  • 25. 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; }
  • 26. 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:
  • 27.
  • 28.
  • 29.
  • 30. 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)) {
  • 31. printf("Queue is fulln"); 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 emptyn"); return -1; } if (queue->front == queue->rear) { item = queue->items[queue->front]; queue->front = -1; queue->rear = -1; } else { item = queue->items[queue->front];
  • 32. 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 emptyn"); 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
  • 33. 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; }