0% found this document useful (0 votes)
33 views75 pages

Chap 02 - Stacks and Queues (Autosaved)

Unit II covers the concepts of Stacks and Queues, including their definitions, operations (push, pop, enqueue, dequeue), and implementations using arrays and linked lists. It also discusses various types of queues such as simple, circular, and priority queues, along with their applications in computer science. Assignment questions focus on practical applications of these data structures, including expression evaluation and algorithm implementation.

Uploaded by

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

Chap 02 - Stacks and Queues (Autosaved)

Unit II covers the concepts of Stacks and Queues, including their definitions, operations (push, pop, enqueue, dequeue), and implementations using arrays and linked lists. It also discusses various types of queues such as simple, circular, and priority queues, along with their applications in computer science. Assignment questions focus on practical applications of these data structures, including expression evaluation and algorithm implementation.

Uploaded by

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

Unit II

Stack & Queue

1
Unit 2
Stacks and Queues:
Syllabus:
Introduction, Stack and queue as ADT,
representation and Implementation of stack and
queue using sequential and linked allocation,
Circular queue and its implementation,
Application of stack for expression evaluation
and conversion, recursion and priority queue.

2
Assignment questions:
1. Consider the stack, where stack is allocated N=6 memory cells,
Suppose initially stack contains, A, D,E,F,G(top of the stack).
Then the following operations are called in order. Show the stack
top and any other situation raised while doing each of the
operation. i) push(stack, k) ii) pop( stack, item) iii)
push(stack, L) iv) Push( stack, S) v) pop(stack, item)
2. Write the prefix form of the infix expression (a-b)/c.
3. convert the expression ((A+B)* C-(D-E)^(F+G)) to equivalent
prefix and postfix notations.
4. Write and explain insert() and delete() used in queue.
5. What is priority queue? Give two example of system in which
priority queue is used.
6. Write and explain iterative procedure to calculate factorial of n.
Stack

4
Basic Principal
•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.

⚫ Stack is a linear data structure which follows a


particular order in which the operations are
performed.
⚫ Insertion of element into stack is called PUSH and
deletion of element from stack is called POP.
⚫ The order may be LIFO(Last In First Out) or
FILO(First In Last Out).
5
Basic Principal
It has two main functions
o push

o pop

• Insertion in a stack is done using push function and removal from a stack is

done using pop function.

Stack allows access to only the last element inserted hence, an item can be

inserted or removed from the stack from one end called the top of the stack. It is

therefore, also called Last-In-First-Out (LIFO) list.

Stack has three properties:

o capacity stands for the maximum number of elements stack can hold.

o size stands for the current size of the stack

o elements is the array of elements.


6
Representation of Stack in Memory
⚫The stack can be implemented into
two ways:

◦Using arrays (Static implementation)


◦Using pointer (Dynamic
implementation)

Prof. K. 7
Stack
Conditions

-1

Prof. K. 8
Stack as an ADT
Set of values for STACK
Stack S is a finite collection of elements having same data type and all
operation are carried out at one end called top.

push
pop
create STACK
isempty
isfull 9
PUSH
Operation
⚫The process of adding one element or item to
the stack is represented by an operation called
as the PUSH operation.

10
PUSH
Operation:
⚫ The process of adding one element or item to the stack is
represented by an operation called as the PUSH operation.
⚫ The new element is added at the topmost position of the stack.
ALGORITHM:
PUSH (STACK, TOP, SIZE, ITEM)
STACK is the array with N elements. TOP is the pointer to the top of
the element of the array. ITEM to be inserted.
Step 1: if TOP = N then [Check Overflow]
PRINT “ STACK is Full or Overflow”
Exit
[End if]
Step 2: TOP = TOP + 1 [Increment the TOP]
Step 3: STACK[TOP] = ITEM [Insert the ITEM]
Step 4: Return
11
POP
Operation
The process of deleting one element or item from
the stack is represented by an operation called
as the POP operation.
When elements are removed continuously from a
stack, it shrinks at same end i.e., top

12
POP
Operation
The process of deleting one element or item from the
stack is represented by an operation called as the POP
operation.
ALGORITHM: POP (STACK, TOP, ITEM)
STACK is the array with N elements. TOP is the pointer to the top of
the element of the array. ITEM to be inserted.
Step 1: if TOP = 0 then [Check Underflow]
PRINT “ STACK is Empty or
Underflow”
Exit
[End if]
Step 2: ITEM = STACK[TOP] [copy the TOP
Step 3: TOP = TOP - 1 Element] [Decrement
Step 4: Return the TOP]

13
PEEK
Operation
The process of returning the top item from the
stack but does not remove it called as the POP
operation.

ALGORITHM: PEEK (STACK, TOP)


STACK is the array with N elements. TOP is the pointer to the
top of the element of the array.
Step 1: if TOP = NULL then [Check Underflow]
PRINT “ STACK is Empty or Underflow”
Exit
[End if]
Step 2: Return (STACK[TOP] [Return the top

element of the stack]


14
Stack using Array

15
Push using Stack PUSH
top
top

16
POP
Pop using Stack
top
top

17
18
19
20
Arithmetic Expression
⚫ An expression is a combination of operands and
operators that after evaluation results in a single value.
· Operand consists of constants and variables.
· Operators consists of {, +, -, *, /, ), ] etc.
⚫ Expression can be
Infix Expression: If an operator is in between two operands, it is called
infix expression.
⚫ Example: a + b, where a and b are operands and + is an operator.
Postfix Expression: If an operator follows the two operands, it is called
postfix expression.
⚫ Example: ab +
Prefix Expression: an operator precedes the two operands, it is called
prefix expression.

21
22
23
24
25
Infix to Postfix Rules
Current Operator Postfix string
symbol Stack
Expression: 1 A A
2 * * A
A * (B + C * D) + E
3 ( *( A
becomes 4 B *( AB
5 + *(+ AB
ABC D * +* E+ 6 C *(+ ABC
7 * *(+* ABC
8 D *(+* ABCD
Postfix notation
9 ) * ABCD*+
is also called as
10 + + ABCD*+*
Reverse Polish
Notation (RPN) 11 E + ABCD*+*E
12 ABCD*+*E+
27
28
29
Application of Stacks
⚫It is used to reverse a word. You push a given word to
stack – letter by letter and then pop letter from the stack.
⚫“Undo” mechanism in text editor.
⚫Backtracking: This is a process when you need to
access the most recent data element in a series of
elements. Once you reach a dead end, you must
backtrack.
⚫Language Processing: Compiler’ syntax check for
matching braces in implemented by using stack.
⚫Conversion of infix expression into prefix and postfix.
⚫Recursion uses stack

30
Implementation of stack
using linked list.
• we can also use linked list to implement stack. Linked list
allocates the memory dynamically.
• In linked list implementation of stack, the nodes are
maintained non-contiguously in the memory. Each node
contains a pointer to its immediate successor node in the stack.
Push operation:
Adding a node to the stack is referred to as push operation. Pushing an
element to a stack in linked list implementation is different from that of an
array implementation. In order to push an element onto the stack, the
following steps are involved.
1. Create a node first and allocate memory to it.
2. If the list is empty then the item is to be pushed as the start node of
the list. This includes assigning value to the data part of the node
and assign null to the address part of the node.
3. If there are some nodes in the list already, then we have to add the
new element in the beginning of the list (to not violate the property
of the stack). For this purpose, assign the address of the starting
element to the address field of the new node and make the new
node, the starting node of the list.
Stack using Linked list :
Deleting a node from the
stack (POP operation)
we need to follow the following steps :
1. Check for the underflow condition: The underflow
condition occurs when we try to pop from an already
empty stack. The stack will be empty if the head
pointer of the list points to null.
2. Adjust the head pointer accordingly: In stack, the
elements are popped only from one end, therefore, the
value stored in the head pointer must be deleted and
the node must be freed. The next node of the head
node now becomes the head node.
Queue

35
Basic Idea
•Queue is an abstract data structure, somewhat similar to Stacks. Unlike
stacks, a queue is open at both its ends. One end is always used to insert
data (enqueue) and the other is used to remove data (dequeue).

• As in stacks, a queue can also be implemented using Arrays,


Linked-lists, Pointers and Structures.

36
Queue
⚫A queue is an ordered collection of items where an
item is inserted at one end called the “rear” and an
existing item is removed at the other end, called
the “front”.
⚫Queue is also called as FIFO list i.e. First-In First-
Out.
⚫In the queue only two operations are allowed enqueue
and dequeue.
⚫Enqueue means to insert an item into back of
the queue.
⚫Dequeue means removing the front item. The people
standing in a railway reservation row are an
example of queue.
Types of
Queues
⚫Queue can be of four
types:
o Simple Queue
o Circular Queue
o Priority Queue

38
Simple
⚫Queue
Simple Queue: In simple queue insertion
occurs at the rear end of the list and
deletion occurs at the front end of the list.

39
Circular
⚫Queue
Circular Queue: A circular queue is a queue
in which all nodes are treated as circular
such that the last node follows the first node.

40
Priority
Queue
⚫A priority queue is a queue that contains
items that have some present priority. An
element can be inserted or removed from
any position depending upon some
priority.

41
Operation on
Queues
⚫Queue( ): It creates a new queue that
is empty.
⚫enqueue(item): It adds a new item to the
rear of the queue.
⚫dequeue( ): It removes the front item
from the queue.
⚫isEmpty( ): It tests to see whether the
queue is empty.
⚫size( ): It returns the number of items in
the queue.
42
Working of Queue
Queue operations work as follows:

1. two pointers FRONT and REAR


2. FRONT track the first element of the queue
3. REAR track the last element of the queue
4. initially, set value of FRONT=0 and REAR to -1
Enqueue Operation

Step 1:check if the queue is full if so then print Queue


overflow
 Step 2: otherwise, increase the REAR index by 1
Step 4:add the new element in the position pointed to
by REAR
Dequeue Operation

Step 1:check if the queue is empty if so then print


queue is underflow
Step 2:otherwise return the value pointed by FRONT
Step 3:increase the FRONT index by 1
Enqueue Operation
Queue is empty

Front=0
Rear=-1 Enqueue(10)

10

Front=0
Front will be incremented
Rear=0 for adding only first
element in queue
Enqueue(20) Enqueue(30)

10 20 30

Front=0 Rear=1 Rear=2

Rear=0
Queue Full Condition
When Rear=SIZE-1 Queue is Full

10 20 30 40 50

Front=0 Rear=4
Dequeue Operation on Queue
On each dequeue front value is incremented by 1

Dequeue() Dequeue()

10 20 30 40 50

Front=0 Front=1 Front=2 Rear=4


Limitations of Simple Queues

In a normal queue, after a bit of insertion and

deletion, there will be non-usable empty

space.
Circular Queue

A circular queue is the extended version of a

regular queue where the last element is connected to the

first element.

Thus forming a circle-like structure.


Circular Queue Representation
How Circular Queue Works
Circular Queue works by the process of circular
increment
i.e. when we try to increment the pointer and we reach
the end of the queue, we start from the beginning of the
queue.
Here, the circular increment is performed by modulo
division with the queue size. That is,
if REAR + 1 == 5 (overflow!),
REAR = (REAR + 1)%5 = 0 (start of queue)
The circular queue work as follows:
• two pointers FRONT and REAR

• FRONT track the first element of the queue

• REAR track the last elements of the queue

• initially, set value of FRONT and REAR to -1


1. Enqueue Operation

• check if the queue is full

• for the first element, set value of FRONT to 0

• circularly increase the REAR index by 1 (i.e. if the

rear reaches the end, next it would be at the start of

the queue)

• add the new element in the position pointed to

by REAR
2. Dequeue Operation

• check if the queue is empty if so then print queue is

underflow

• Otherwise return the value pointed by FRONT

• circularly increase the FRONT index by 1

• for the last element, set the values of FRONT to

zero
Applications of Queue:
There are several applications of queues in computer science.

1. Implements the various aspects of an operating systems.

2. CPU scheduling in Multiprogramming environment- single

CPU has to serve more than one program simultaneously.

3. Operating System maintains a queue of processes that are

ready to process or that are waiting for particular event to

occur.
57
Queue using Linked List

58
Basic Idea
•Basic idea:
• Create a linked list to which items would be added to one end
and deleted from the other end.
• Two pointers will be maintained:
• One pointing to the beginning of the list (point from where
elements will be deleted).
• Another pointing to the end of the list (point where new
elements will be inserted).
Rear

Front DELETION INSERTION


59
Queue: Linked List Structure

ENQUEUE

front rear
Queue: Linked List Structure

DEQUEUE

front rear

61
Example :Queue using Linked List
struct qnode
{
int val;
struct qnode *next;
};

struct queue
{
struct qnode *qfront, *qrear;
};
typedef struct queue QUEUE;

void enqueue (QUEUE *q,int element)


{
struct qnode *q1;
q1=(struct qnode *)malloc(sizeof(struct qnode));
q1->val= element;
q1->next=q->qfront;
q->qfront=q1;
}

62
Example :Queue using Linked List
int size (queue *q)
{
queue *q1;
int count=0;
q1=q;
while(q1!=NULL) int dequeue (queue *q)
{ {
q1=q1->next; int val;
count++; queue *q1,*prev;
} q1=q;
return count; while(q1->next!=NULL)
} {
prev=q1;
q1=q1->next;
}
val=q1->val;
int peek (queue *q)
prev->next=NULL;
{
free(q1);
queue *q1;
return (val);
q1=q;
}
while(q1->next!=NULL)
q1=q1->next;
return (q1->val);
}
Problem With Array Implementation
•The size of the queue depends on the number and order of enqueue and
dequeue.
•It may be situation where memory is available but enqueue is not possible.

ENQUEUE DEQUEUE
Effective queuing storage area of array gets reduced.
0 N

front
front rearrear

Use of circular array indexing


65
66
Priority Queue:

A priority queue is a collection of elements such that each


element has been assigned a priority and such that the order in
which elements are deleted and processed comes from the
following rules:
1. An element of higher priority is processed before any element
of lower priority.
2. two elements with same priority are processed according to
the order in which they were added to the queue.

A prototype of a priority queue is time sharing system: programs


of high priority are processed first, and programs with the same
priority form a standard queue.

An efficient implementation for the Priority Queue is to use heap,


which in turn can be used for sorting purpose called heap sort.
What is recursion? Write a C program for GCD using
recursion.
∙ A procedure that contains a procedure call to itself or a
procedure call to second procedure which eventually
causes the first procedure to be called is known as
recursive procedure.
∙ There are two important conditions that must be satisfied by
any recursive procedure
a. Each time a procedure calls itself it must be nearer in some
sense to a solution
b. There must be a decision criterion for stopping the process
or computation
∙ There are two types of recursion
o Primitive Recursion: this is recursive defined function. E.g.
Factorial function
o Non-Primitive Recursion: this is recursive use of
procedure. E.g. Find GCD of given two nunbers
Thanks

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