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

STACK

The document discusses stacks as a linear data structure that follows the LIFO (last-in, first-out) principle and can be implemented using either arrays or linked lists. It describes the basic stack operations of push, pop, peek, isEmpty and isFull. It provides pseudocode for implementing stack operations like push and pop in both array-based and linked list-based stacks.

Uploaded by

Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

STACK

The document discusses stacks as a linear data structure that follows the LIFO (last-in, first-out) principle and can be implemented using either arrays or linked lists. It describes the basic stack operations of push, pop, peek, isEmpty and isFull. It provides pseudocode for implementing stack operations like push and pop in both array-based and linked list-based stacks.

Uploaded by

Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 124

STACK and QUEUE

Click to add text

Mr. Mahendra Pratap Yadav


Assistant Professor
School of Computing Science and Engineering
VIT Bhopal University
mahendra.pratap@vitbhopal.ac.in
Stack- Outline
*Stack
* Basic principles
* Operation of stack
* Stack using Array
* Stack using Linked List
* Applications of stack
Basic Idea
•A stack is an Abstract Data Type (ADT), commonly used in
most programming languages. It is named stack as it behaves
like a real-world stack, for example – a deck of cards or a pile
of plates, etc.

3
Stack ADT Interface
The main functions in the Stack ADT are (S is the stack)

boolean isEmpty(); // return true if empty

boolean isFull(S); // return true if full

void push(S, item); // insert item into stack

void pop(S); // remove most recent item

void clear(S); // remove all items from stack

Item top(S); // retrieve most recent item

Item topAndPop(S); // return & remove most recent item

5/4/2022 CS 201
Axioms

5
What is a Stack?
➢A stack is an Abstract Data Type (ADT),
commonly used in most programming
languages.
➢ A Stack is a linear data structure that
follows the LIFO (Last-In-First-
Out) principle.
➢ It contains only one pointer top
pointer pointing to the topmost element
of the stack.
What is a Stack?
➢ Whenever an element is added in the
stack, it is added on the top of the stack,
and the element can be deleted only
from the stack.
Stack Representation

•Can be implemented by means of Array, or Linked List.


•Stack can either be a fixed size or dynamic.
8
Stack Representation
Basic Idea

10
push

pop

create
STACK
isempty

isfull

11
STACK: Last-In-First-Out (LIFO)
•void push (stack *s, int element);
/* Insert an element in the stack */
•int pop (stack *s);
/* Remove and return the top element
*/
•void create (stack *s);
/* Create a new stack */
•int isempty (stack *s);
/* Check if stack is empty */
•int isfull (stack *s);
/* Check if stack is full */
Assumption: stack contains integer elements!
12
Array implementation of stacks
To implement a stack, items are inserted and removed at
the same end (called the top)
Efficient array implementation requires that the top of the
stack be towards the center of the array, not fixed at one
end
To use an array to implement a stack, you need both the
array itself and an integer
The integer tells you either:
Which location is currently the top of the stack, or
How many elements are in the stack

13
Pushing and popping
0 1 2 3 4 5 6 7 8 9
stk:
17 23 97 44

top = 3 or count = 4

If the bottom of the stack is at location 0, then an empty


stack is represented by top = -1 or count = 0
To add (push) an element, either:
Increment top and store the element in stk[top], or
Store the element in stk[count] and increment count
To remove (pop) an element, either:
Get the element from stk[top] and decrement top, or
Decrement count and get the element in stk[count]

14
After popping
0 1 2 3 4 5 6 7 8 9
stk:
17 23 97 44

top = 2 or count = 3

When you pop an element, do you just leave the “deleted”


element sitting in the array?

15
Error checking
There are two stack errors that can occur:
Underflow: trying to pop (or peek at) an empty stack
Overflow: trying to push onto an already full stack
For underflow, you should throw an exception
If you don’t catch it yourself, Java will throw an ArrayIndexOutOfBounds
exception
You could create your own, more informative exception
For overflow, you could do the same things
Or, you could check for the problem, and copy everything into a new, larger
array

16
Linked-list implementation of
stacks
Since all the action happens at the top of a stack, a singly-
linked list (SLL) is a fine way to implement it
The header of the list points to the top of the stack

myStack:

44 97 23 17

Pushing is inserting an element at the front of the list


Popping is removing an element from the front of the list

17
Linked-list implementation details
With a linked-list representation, overflow will not
happen (unless you exhaust memory, which is
another kind of problem)
Underflow can happen, and should be handled the
same way as for an array implementation
When a node is popped from a list, and the node
references an object, the reference (the pointer in the
node) does not need to be set to null
Unlike an array implementation, it really is removed--you can no longer get to
it from the linked list
Hence, garbage collection can occur as appropriate

18
Basic Operations
➢ Stack operations may involve initializing
the stack, using it and then de-initializing
it. Apart from these basic stuffs, a stack
is used for the following two primary
operations −
a. push() − Pushing (storing) an
element on the stack.
b. pop() − Removing (accessing) an
element from the stack.
Basic Operations
➢ To use a stack efficiently, we need to
check the status of stack as well. For the
same purpose, the following
functionality is added to stacks −
a. peek() − get the top data element of
the stack, without removing it.
b. isFull() − check if stack is full.
c. isEmpty() − check if stack is empty.
Stack using Array

21
Push using Stack

PUSH

top
top

22
Pop using Stack

POP

top
top

23
Stack using Linked List

24
Push using Linked List

PUSH OPERATION

top

Autumn 2016 25 Autumn 2016


Pop using Linked List

POP OPERATION

top

26
Basic Idea
•In the array implementation, we would:
•Declare an array of fixed size (which determines the maximum size
of the stack).
•Keep a variable which always points to the “top” of the stack.
•Contains the array index of the “top” element.

•In the linked list implementation, we would:


•Maintain the stack as a linked list.
•A pointer variable top points to the start of the list.
•The first element of the linked list is considered as the stack top.

27
Declaration

#define MAXSIZE 100 struct lifo


{
struct lifo int value;
{ struct lifo *next;
int st[MAXSIZE]; };
int top; typedef struct lifo
}; stack;
typedef struct lifo
stack; stack *top;
stack s;

ARRAY LINKED LIST

28
Stack Creation

void create (stack *s) void create (stack **top)


{ {
s->top = -1; *top = NULL;
/* s->top points to /* top points to NULL,
last element indicating empty
pushed in; stack */
initially -1 */ }
}

ARRAY LINKED LIST

29
Push Operation
The process of putting a new data element onto stack is known
as a Push Operation. Push operation involves a series of steps −

❖ Step 1 − Checks if the stack is full.

❖ Step 2 − If the stack is full, produces an error and exit.

❖ Step 3− If the stack is not full, increments top to point


next empty space.

❖ Step 4 − Adds data element to the stack location,


where top is pointing.

❖ Step 5 − Returns success.


30
Push Operation

31
Pushing an element into stack
Algorithm to push an element into stack− Array

32
Pushing an element into stack
Algorithm to push an element into stack− Linked List

33
Pushing an element into stack

void push (stack *s, int element) void push (stack **top, int element)
{ {
stack *new;
if (s->top == (MAXSIZE-1))
{ new = (stack *)malloc (sizeof(stack));
printf (“\n Stack overflow”); if (new == NULL)
exit(-1); {
} printf (“\n Stack is full”);
exit(-1);
else
}
{
s->top++; new->value = element;
s->st[s->top] = element; new->next = *top;
} *top = new;
}
}

ARRAY LINKED LIST


34
POP Operation
Accessing the content while removing it from the stack, is
known as a Pop Operation. A Pop operation may involve the
following steps −
❖ Step 1 − Checks if the stack is empty

❖ Step 2 − If the stack is empty, produces an error and exit.

❖ Step 3− If the stack is not empty, accesses the data


element at which top is pointing.

❖ Step 4 − Decreases the value of top by 1.

❖ Step 5 − Returns success.


35
Pop Operation

36
Popping an element from stack

Algorithm to pop an element− Array

37
Popping an element from stack

Algorithm to pop an element− Linked List

38
Popping an element from stack

int pop (stack **top)


{
int pop (stack *s) int t;
{ stack *p;
if (s->top == -1) if (*top == NULL)
{ {
printf (“\n Stack underflow”); printf (“\n Stack is empty”);
exit(-1);
exit(-1); }
} else
else {
{ t = (*top)->value;
p = *top;
return (s->st[s->top--]); *top = (*top)->next;
} free (p);
} return t;
}
}

ARRAY LINKED LIST


39
peek()
Algorithm of peek() function −

begin procedure peek


return stack[top]
end procedure

Implementation of peek() function in C programming language −

int peek()
{
return stack[top];
}
Checking for Stack Full
Algorithm of isfull() function −

begin procedure isfull


if top equals to MAXSIZE
return true
else
return false
endif
end procedure
Checking for Stack Full

int isempty (stack *s) int isempty (stack *top)


{ {
if (s->top == -1) if (top == NULL)
return 1; return (1);
else else
return (0); return (0);
} }

ARRAY LINKED LIST

42
Checking for stack empty
Algorithm of isempty() function −

begin procedure isempty


if top is less than 1
return true
else
return false
endif
end procedure

Implementation of isempty() function in C programming


language is slightly different. We initialize top at -1, as the
index in array starts from 0. So we check if the top is below
zero or -1 to determine if the stack is empty.
Checking for stack empty

int isempty (stack *s) int isempty (stack *top)


{ {
if (s->top == -1) if (top == NULL)
return 1; return (1);
else else
return (0); return (0);
} }

ARRAY LINKED LIST

44
Application of Stack Data Structure
•Stack is used for expression evaluation
•Stack is used for parenthesis matching while working
with expressions.
• Stack is used in expression conversion. For example,
infix to postfix or prefix to postfix
•Stack is used in memory management
• It is used in java virtual machine
• It is used for the Backtracking problem-solving method
Application of Stack Data Structure
•It is used in string parsing or string reversal.
•Stack is used to matching the HTML tags in web
development
•Stack is also used in function call for recursive
functions.
Applications of Stacks
•Direct applications:
•Page-visited history in a Web browser
•Undo sequence in a text editor
•Chain of method calls in the Java Virtual Machine
•Validate XML

•Indirect applications:
•Auxiliary data structure for algorithms
•Component of other data structures

47
48
Partial Table of Operator Precedence and
Associativity
Operator Associativity

() ++ (postfix) -- (postfix) left to right

+(unary) -(unary) ++(prefix) --(prefix) right to left

* / % left to right

+ - left to right

= += -= right to left
Operators on the top line have the highest precedence.
Precedence decreases line-by-line going down the table.
All operators on the same line have equal precedence.
49
Infix and Postfix Notations
•Infix: operators placed between operands:
A+B*C
•Postfix: operands appear before their operators:-
ABC*+
•There are no precedence rules to learn in postfix notation, and
parentheses are never needed

50
Infix to Postfix

Infix Postfix
A+B AB+
A+B*C ABC*+
(A + B) * C AB+C*
A+B*C+D ABC*+D+
(A + B) * (C + D) AB+CD+*
A*B+C*D AB*CD*+

A + B * C → (A + (B * C)) → (A + (B C *) ) → A B C * +

A + B * C + D → ((A + (B * C)) + D ) → ((A + (B C*) )+ D) →


((A B C *+) + D) → A B C * + D +
51
Evaluation of postfix expression -

52
Evaluation of postfix expression -

53
Evaluation of postfix expression -

54
Infix to postfix conversion
•Use a stack for processing operators (push and pop
operations).
•Scan the sequence of operators and operands from left to right
and perform one of the following:
•output the operand,
•push an operator of higher precedence,
•pop an operator and output, till the stack top contains operator of a lower precedence
and push the present operator.

55
The algorithm steps
1. Print operands as they arrive.
2. If the stack is empty or contains a left parenthesis on top, push the incoming
operator onto the stack.
3. If the incoming symbol is a left parenthesis, push it on the stack.
4. If the incoming symbol is a right parenthesis, pop the stack and print the
operators until you see a left parenthesis. Discard the pair of parentheses.
5. If the incoming symbol has higher precedence than the top of the stack, push it
on the stack.
6. If the incoming symbol has equal precedence with the top of the stack, use
association. If the association is left to right, pop and print the top of the stack
and then push the incoming operator. If the association is right to left, push the
incoming operator.
7. If the incoming symbol has lower precedence than the symbol on the top of the
stack, pop the stack and print the top operator. Then test the incoming operator
against the new top of stack.
8. At the end of the expression, pop and print all operators on the stack. (No
parentheses should remain.)

56
Infix to Postfix Conversion
Requires operator precedence information
Operands:
Add to postfix expression.
Close parenthesis:
pop stack symbols until an open parenthesis appears.
Operators:
Pop all stack symbols until a symbol of lower precedence appears.
Then push the operator.
End of input:
Pop all remaining stack symbols and add to the expression.

57
Infix to Postfix Conversion

58
Infix to Postfix Conversion

59
Example - Conversion Infix to Postfix

60
Example - Conversion Infix to Postfix

61
Queue

62
What is a queue?
It is an ordered group of homogeneous items of
elements.
Queues have two ends:
Elements are added at one end.
Elements are removed from the other end.
The element added first is also removed first
(FIFO: First In, First Out).
Queue

• Non-primitive linear data structure.


• A new element is added at one end called rear end and the
existing elements are deleted from the other end called
front end.
• This mechanism is called First-In-First-Out (FIFO).

e.g. People standing in Queue for Movie Ticket


Fig: Model of a Queue
Elements of queue:-
Front: -
This end is used for deleting an element from a queue.
Initially front end is set to -1. Front end is incremented by
one when a new element has to be deleted from queue.
Rear: -
This end is used for inserting an element in a queue.
Initially rear end is set to -1. rear end is incremented by one
when a new element has to be inserted in queue.
Queue Representation

❖ Same as stack, queue can also be implemented using


Array, Linked-list, Pointer and Structures.
Queue as ADT(abstract data type.)

Queue is a data structure which allows a programmer to insert


an element at one end known as “Rear” and to delete an
element at other end known as “Front”.
Queue is an abstract data type because it not only allows
storing a elements but also allows to perform certain
operation on these elements.
Queue as ADT(abstract data type.)

These operations are as follows.


Initialize()
enqueue()
dequeue()
Isempty()
Isfull()
Display()

Elements of queue:-
Front
Rear
array
Basic Operations
❖ Queue operations may involve initializing or defining the
queue, utilizing it and then completing erasing it from
memory.

❖ enqueue − add store an item to the queue.


❖ dequeue − remove access an item from the queue.

❖ Few more functions are required to make above


mentioned queue operation efficient. These are
❖ peek − get the element at front of the queue without
removing it
❖ isfull − checks if queue is full.
❖ isempty − checks if queue is empty.
Basic Operations
❖ Queue operations may involve initializing or defining the
queue, utilizing it and then completing erasing it from
memory.

❖ enqueue − add store an item to the queue.


❖ dequeue − remove access an item from the queue.

❖ Few more functions are required to make above


mentioned queue operation efficient. These are
❖ peek − get the element at front of the queue without
removing it
❖ isfull − checks if queue is full.
❖ isempty − checks if queue is empty.
Queue Specification
Definitions:
MAX_ITEMS: Max number of items that might be on the
queue
ItemType: Data type of the items on the queue

• Operations
– MakeEmpty
– Boolean IsEmpty
– Boolean IsFull
– Enqueue (ItemType newItem)
– Dequeue (ItemType& item)
Peek ()
a. This function helps to see the data at the front of the
queue. Algorithm of peek function − .

begin procedure peek

return queue[front]

end procedure
a. Implementation of peek function in C programming language
int peek()
{
return queue[front];
}
isfull()
a. As we are using single dimension array to implement
queue, we just check for the rear pointer to reach at
MAXSIZE to determine that queue is full. In case we
maintain queue in a circular linkedlist, the algorithm
will differ. Algorithm of isfull function −
begin procedure isfull
if rear equals to MAXSIZE
return true
else
return false
endif

end procedure
isfull()
a. Implementation of isfull function in C programming language

bool isfull()
{
if(rear == MAXSIZE - 1)
return true;
else
return false;
}
isempty()
a. Algorithm of isempty function−
begin procedure isempty
if front is less than MIN OR front is greater than rear
return true
else
return false
endif
end procedure

If value of front is less than MIN or 0, it tells that queue is not


yet initialized, hence empty
isempty()
a. Implementation of peek function in C programming
language

bool isempty()
{
if(front < 0 || front > rear)
return true;
else
return false;
}
Enqueue (ItemType newItem)
As queue maintains two data pointers, front and rear,
its operations are comparatively more difficult to
implement than stack.

Function: Adds newItem to the rear of the queue.


Preconditions: Queue has been initialized and is not
full.
Postconditions: newItem is at rear of queue.
Enqueue Operation
The following steps should be taken to enqueue insert data
into a queue −
❖ Step 1 − Check if queue is full.

❖ Step 2 − − If queue is full, produce overflow error and exit.

❖ Step 3− If queue is not full, increment rear pointer to point


next empty space.

❖ Step 4 − Add data element to the queue location, where


rear is pointing.

❖ Step 5 − Returns success.


Enqueue Operation
Algorithm for enqueue operation
Enqueue Operation
Implementation of enqueue in C programming language −

int enqueue(int data)


if(isfull())
return 0;

rear = rear + 1;
queue[rear] = data;
return 1;
end procedure
Dequeue (ItemType& item)
Function: Removes front item from queue and returns it in
item.
Preconditions: Queue has been initialized and is not empty.
Postconditions: Front element has been removed from
queue and item is a copy of removed element.
Dequeue Operation
Accessing data from queue is a process of two tasks − access
the data where front is pointing and remove the data after
access. The following steps are taken to perform dequeue
operation −
❖ Step 1 − Check if queue is empty.
❖ Step 2 − If queue is empty, produce underflow error and exit.
❖ Step 3− − If queue is not empty, access data where front is
pointing.
❖ Step 4 − − Increment front pointer to point next available data
element.
❖ Step 5 − Returns success.
Dequeue Operation
Algorithm for dequeue operation
Enqueue Operation
Implementation of enqueue in C programming language −

int dequeue()
{
if(isempty())
return 0;

int data = queue[front];


front = front + 1;;
return data;
}
Make front point to the element preceding the front
element in the queue (one memory location will be
wasted).
Initialize front and rear
Queue is empty
now!!
rear == front
Array implementation of queues
A queue is a first in, first out (FIFO) data structure
This is accomplished by inserting at one end (the rear) and
deleting from the other (the front)

0 1 2 3 4 5 6 7
myQueue:
17 23 97 44

front = 0 rear = 3

To insert: put new element in location 4, and set rear to 4


To delete: take element from location 0, and set front to 1

93
Array implementation of queues
front = 0 rear = 3

Initial queue: 17 23 97 44

After insertion: 17 23 97 44 333

After deletion: 23 97 44 333

front = 1 rear = 4

Notice how the array contents “crawl” to the right as elements


are inserted and deleted
This will be a problem after a while!
94
Circular arrays
We can treat the array holding the queue elements as
circular (joined at the ends)

0 1 2 3 4 5 6 7
myQueue:
44 55 11 22 33

rear = 1 front = 5

Elements were added to this queue in the order 11, 22, 33,
44, 55, and will be removed in the same order
Use: front = (front + 1) % myQueue.length;
and: rear = (rear + 1) % myQueue.length;
95
Full and empty queues
If the queue were to become completely full, it would look
like this:
0 1 2 3 4 5 6 7
myQueue:
44 55 66 77 88 11 22 33

rear = 4 front = 5

If we were then to remove all eight elements, making the queue


completely empty, it would look like this:

0 1 2 3 4 5 6 7
myQueue:

rear = 4 front = 5
This is a problem! 96
Full and empty queues: solutions
Solution #1: Keep an additional variable

0 1 2 3 4 5 6 7
myQueue:
44 55 66 77 88 11 22 33

count = 8 rear = 4 front = 5

Solution #2: (Slightly more efficient) Keep a gap between


elements: consider the queue full when it has n-1 elements

0 1 2 3 4 5 6 7
myQueue:
44 55 66 77 11 22 33

rear = 3 front = 5
97
Linked-list implementation of queues
In a queue, insertions occur at one end, deletions at the
other end
Operations at the front of a singly-linked list (SLL) are
O(1), but at the other end they are O(n)
Because you have to find the last element each time
BUT: there is a simple way to use a singly-linked list to
implement both insertions and deletions in O(1) time
You always need a pointer to the first thing in the list
You can keep an additional pointer to the last thing in the list

98
SLL implementation of queues
In an SLL you can easily find the successor of a node,
but not its predecessor
Remember, pointers (references) are one-way
If you know where the last node in a list is, it’s hard to
remove that node, but it’s easy to add a node after it
Hence,
Use the first element in an SLL as the front of the queue
Use the last element in an SLL as the rear of the queue
Keep pointers to both the front and the rear of the SLL

99
Enqueueing a node
Node to be
last enqueued
first

44 97 23 17

To enqueue (add) a node:


Find the current last node
Change it to point to the new last node
Change the last pointer in the list header

100
Dequeueing a node
last
first

44 97 23 17

To dequeue (remove) a node:


Copy the pointer from the first node into the header

101
Queue implementation details
With an array implementation:
you can have both overflow and underflow
you should set deleted elements to null

With a linked-list implementation:


you can have underflow
overflow is a global out-of-memory condition
there is no reason to set deleted elements to null

102
‘Queue Full(Overflow)’ Condition

Queue Full(Overflow):
Inserting an element in a queue which is already full is known as Queue
Full condition (Rear = Max-1).
When the queue is fully occupied and enqueue() operation is called
queue overflow occurs.

Example: Queue Full:


Before inserting an element in queue 1st check whether space is
available for new element in queue. This can be done by checking
position of rear end. Array begins with 0th index position & ends with
max-1 position. If numbers of elements in queue are equal to size of
queue i.e. if rear end position is equal to max-1 then queue is said to be
full. Size of queue = 4
‘Queue Empty(Underflow)’ Condition

Queue Empty:
Deleting an element from queue which is already empty is known as
Queue Empty condition (Front = Rear = -1)
When the queue is fully empty and dequeue() operation is called
queue underflow occurs.

Queue Empty:
Before deleting any element from queue check whether there is an
element in the queue. If no element is present inside a queue & front
& rear is set to -1 then queue is said to be empty.
Size of queue = 4
Front = Rear = -1
Disadvantages of linear queue
On deletion of an element from existing
queue, front pointer is shifted to next
position.
This results into virtual deletion of an
element.
By doing so memory space which was
occupied by deleted element is wasted and
hence inefficient memory utilization is
occur.
Overcome disadvantage of linear queue:

To overcome disadvantage of linear queue,


circular queue is use.
We can solve this problem by joining the front and
rear end of a queue to make the queue as a circular
queue .
Circular queue is a linear data structure. It follows
FIFO principle.
In circular queue the last node is connected back to
the first node to make a circle.
Overcome disadvantage of linear queue:

It is also called as “Ring buffer”.


Items can inserted and deleted from a queue in
O(1) time.
Representation Of
Queues
1.Using an array
2.Using linked list
Types Of Queue

1. Circular Queue

2. Dequeue (Double Ended Queue)

3. Priority Queue
CIRCULAR QUEUE
A queue, in which the last node is connected back to the
first node to form a cycle, is called as circular queue.
Circular queue are the queues implemented in circular
form rather than in a straight line.
Circular queues overcome the problem of unutilized
space in linear queue implemented as an array.
The main disadvantage of linear queue using array is that
when elements are deleted from the queue, new elements
cannot be added in their place in the queue, i.e. the
position cannot be reused.
CIRCUL
AR
QUEUE
CIRCULAR QUEUE IMPLEMENTATION

After rear reaches the last position, i.e. MAX-1 in


order to reuse the vacant positions, we can bring
rear back to the 0th position, if it is empty, and
continue incrementing rear in same manner as
earlier.
Thus rear will have to be incremented circularly.
For deletion, front will also have to be
incremented circularly..
Enqueue(Insert) operation on
Circular Queue:
Step 1: Check for queue full
If rear=max–1 and front=0 or if front=rear+1 then
circular queue is full and insertion operation is
not possible. otherwise go to step 2
Step 2: Check position of rear pointer
If rear=max–1
then set rear=0 otherwise increment rear by 1.
rear=(rear+1)%MAX
Step 3: Insert element at the position pointer by rear
pointer.
q[rear]=Data
Step 4: Check the position of front pointer
If front=–1 then set front as 0.
Dequeue (Delete) operation on
Circular Queue:
Step 1: Check for queue empty if (front = -1)
then circular queue is empty and deletion operation
is not possible. otherwise go to step 2
Step 2: Check for position of front and rear pointers.
if front = rear then
Data = q[front];
set front=rear=-1
Step 3: Check position of front
if front = Max-1
Data = q[front];
then set front=0;
otherwise
Data = q[front];
front = (front+1)%MAX
PRIORITY QUEUE
A priority Queue is a collection of elements where
each element is assigned a priority and the order in
which elements are deleted and processed is
determined from the following rules:
1) An element of higher priority is processed before
any element of lower priority.
2) Two elements with the same priority are processed
according to the order in which they are added to the
queue.
The priority queue implementation
The priority queue is again implemented in two way
1. array/sequential representation.
2. Dynamic/ linked representation.
In priority queue node is divided into three parts
PRIORITY QUEUE
An example where priority queue are used is in
operating systems.
The operating system has to handle a large number
of jobs.
These jobs have to be properly scheduled.
The operating system assigns priorities to each type
of job.
The jobs are placed in a queue and the job with the
highest priority will be executed first.
PRIORITY QUEUE
Advantages:-
Preferences to the higher priority process are
added at the beginning.
Keep the list sorted in increasing order.
Applications of Queue
Queue, as the name suggests is used whenever we need
to have any group of objects in an order in which the first
one coming in, also gets out first while the others wait
for there turn, like in the following scenarios :
Serving requests on a single shared resource, like a printer, CPU
task scheduling etc.
In real life, Call Center phone systems will use Queues, to hold
people calling them in an order, until a service representative is
free.
Handling of interrupts in real-time systems. The interrupts are
handled in the same order as they arrive, First come first served.
Application of Queue Data Structure
•The queue is used as a waiting list when the resource is
to be shared with multiple systems. For example, CPU
scheduling or disk scheduling
•It is used in the operating system for FCFS scheduling,
semaphores, buffer for devices and spooling the printers
•Queues are used in routers and switches
•In networking, the queue is used when data is
transferred asynchronously
Application of Queue Data Structure
•Used in maintaining the playlist in media players
•Used to handle interrupts in the operating system
•The queue is used in the round-robin scheduling
algorithm
Difference between Stack & Queue
Stack Queue

The stack is based on LIFO(Last In First Out) The queue is based on FIFO(First In First Out)
principle principle.

Insertion Operation is called Push Operation Insertion Operation is called Enqueue Operation

Deletion Operation is called Pop Operation Deletion Operation is called Dequeue Operation

Push and Pop Operation takes place from one Enqueue and Dequeue Operation takes place
end of the stack from a different end of the queue

The most accessible element is called Top and The insertion end is called Rear End and the
the least accessible is called the Bottom of the deletion end is called the Front End.
stack
Simple Implementation Complex implementation in comparison to
stack
Only one pointer is used for performing Two pointers are used to perform operations
operations
Difference between Stack & Queue
Stack Queue

Empty condition is checked using Empty condition is checked using


Top==-1 Front==-1||Front==Rear+1
.
Full condition is checked using Full condition is checked using
Top==Max-1 Rear==Max-1
There are no variants available for stack There are three types of variants i.e circular queue,
double-ended queue and priority queue

Can be considered as a vertical collection Can be considered as a horizontal


visual collection visual

Used to solve the recursive type problems Used to solve the problem having sequential
processing
THANK YOU

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy