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

Lab 06 Stack & Queue

This document outlines a Data Structures lab session focusing on stacks and queues as abstract data types. It details the definitions, types, basic operations, and applications of stacks and queues, including infix to postfix and prefix conversions, as well as circular queues. Additionally, it includes exercises for practical implementation of these concepts, such as separating even and odd values in stacks and creating a ticketing system using queues.

Uploaded by

alishba.subhani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab 06 Stack & Queue

This document outlines a Data Structures lab session focusing on stacks and queues as abstract data types. It details the definitions, types, basic operations, and applications of stacks and queues, including infix to postfix and prefix conversions, as well as circular queues. Additionally, it includes exercises for practical implementation of these concepts, such as separating even and odd values in stacks and creating a ticketing system using queues.

Uploaded by

alishba.subhani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Data Structures Lab

Session 6
Course: Data Structures (CL2001) Semester: Fall 2024
Instructor: Alishba Subhani T.A:

 Maintain discipline during the lab.


 Just raise hand if you have any problem.
 Get your lab checked at the end of the session.

Stack as an Abstract Data Type

Stack is a linear data structure based on LIFO in which the insertion of a new element and
removal of an existing element takes place at the same end represented as the top of the stack.

To implement the stack, it is required to maintain the pointer to the top of the stack , which is
the last element to be inserted because we can access the elements only on the top of the stack.
Types of Stack Data Structure:

 Fixed Size Stack : As the name suggests, a fixed size stack has a fixed size and
cannot grow or shrink dynamically. If the stack is full and an attempt is made to add an
element to it, an overflow error occurs. If the stack is empty and an attempt is made to remove
an element from it, an underflow error occurs.

 Dynamic Size Stack : A dynamic size stack can grow or shrink dynamically. When
the stack is full, it automatically increases its size to accommodate the new element, and when
the stack is empty, it decreases its size. This type of stack is implemented using a linked list, as
it allows for easy resizing of the stack.

Basic Operations on Stack Data Structure:

In order to make manipulations in a stack, there are certain operations provided to us.

 push() to insert an element into the stack (check if there is space available in the stack,
increment the top and insert the value at this new top position)

 pop() to remove an element from the stack (check if there is an element available in
stack, return the top element and decrement the top)

 top() Returns the top element of the stack. (simply returns the element at top)

 isEmpty() returns true if stack is empty else false. (if top == -1, stack is empty)

 isFull() returns true if the stack is full else false. (if top == MAX, stack is empty)
Application Of Stacks (Convert INFIX to POSTFIX)
Complete Algorithm for Infix to Postfix Conversion Using Stack

1. Initialize an empty stack and an empty output list.


2. Read each token (operand, operator, or parenthesis) from left to right in the infix
expression.
3. For each token:
 If it's an operand (number/variable), add it to the output.
 If it's a left parenthesis “(”, push it onto the stack.
 If it's a right parenthesis “)”, pop the stack to the output until “(” is found, and
discard “(”. If stack becomes empty before encountering ‘(‘, then it’s an invalid
expression.
 If it's an operator, check its precedence and associativity:
o If left-associative, pop from the stack to the output all operators of equal
or higher precedence, then push the current operator.
o If right-associative, push the operator directly onto the stack.
4. After reading the expression, pop all operators from the stack to the output.
5. Return the final output list as the postfix expression.

Application Of Stacks (Convert INFIX to PREFIX)


Steps for Converting Infix to Prefix Using Stacks

1. Reverse the Infix Expression:


o Reverse the given infix expression.
o Replace left parentheses ( with right parentheses ) and vice versa. This ensures
that when the reversed expression is processed, parentheses still behave as
expected.
2. Apply Infix to Postfix Algorithm:
o Now, apply the standard infix-to-postfix conversion algorithm to the reversed
expression (with swapped parentheses). This step gives you a postfix expression
for the reversed infix expression.
3. Reverse the Postfix Expression:
o After obtaining the postfix expression from the reversed infix expression, reverse
the result to get the prefix expression.

Analyze (A+B/C*(D+C)-F)
Queue as an Abstract Data Type
A queue is a linear data structure based on FIFO (First In, First Out) in which the insertion of a
new element takes place at one end, called the rear, and the removal of an existing element takes
place at the other end, called the front. This structure is useful when order preservation is
required in data processing, as elements are dequeued in the same order they are enqueued.

To implement a queue, it is essential to maintain pointers to both the front and rear of the queue.
The front points to the element that will be removed next, and the rear points to where the next
element will be inserted.

Types of Queue Data Structures:

Fixed Size Queue: As the name suggests, a fixed-size queue has a predetermined size that
cannot grow or shrink dynamically. If the queue is full and an attempt is made to add an element,
an overflow error occurs. If the queue is empty and an attempt is made to remove an element, an
underflow error occurs.

Dynamic Size Queue : A dynamic size queue can grow and shrink dynamically based on the
number of elements. When the queue is full, its size automatically increases to accommodate
more elements, and when it becomes empty, the size can decrease. This type of queue is
typically implemented using a linked list to allow for easy resizing.

Basic Operations on Queue Data Structure:

To manipulate elements in a queue, the following operations are typically provided:

 enqueue(): Inserts an element into the queue. (Check if there is space available, then
increment the rear pointer and insert the value at this new rear position)
 dequeue(): Removes an element from the queue. (Check if the queue is not empty, then
return the element at the front and increment the front pointer)
 front(): Returns the element at the front of the queue. (Simply returns the element at the
front without removing it)
 isEmpty(): Returns true if the queue is empty, else returns false. (If front == rear or front
exceeds rear, the queue is empty)
 isFull(): Returns true if the queue is full, else returns false. (If the rear equals the
maximum size of the queue, it's full)

Drawback:

One drawback of the linear queue is that it doesn't reuse space, so after a few dequeue
operations, the queue may become full even though there are free slots at the beginning. A
circular queue overcomes this limitation by reusing space.

Circular Queue

A Circular Queue is a more efficient variation of the standard queue, where the last position is
connected back to the first position to make a circle. This allows the queue to use the available
space more efficiently by overcoming the limitations of the linear queue, which suffers from the
"false overflow" problem even when there is space available at the front. In a circular queue,
when the rear reaches the last position, it can wrap around to the beginning, provided there is
free space.

Properties of a Circular Queue:

 Front: Points to the frontmost element of the queue.


 Rear: Points to the position where the next element will be inserted.
 The queue is full when the next position of the rear (i.e., (rear + 1) % size) equals
the front.
 The queue is empty when the front equals the rear.

Basic Operations in Circular Queue:

 enqueue(): Insert an element into the queue.


o Check if the queue is full using the condition (rear + 1) % size == front.
o If not full, increment rear using rear = (rear + 1) % size and insert the
element at the new rear position.
 dequeue(): Remove an element from the queue.
o Check if the queue is empty using the condition front == rear.
o If not empty, return the element at the front, then increment front using front
= (front + 1) % size.
 front(): Returns the front element of the queue.
o Simply returns the element at front, provided the queue is not empty.
 isEmpty(): Returns true if the queue is empty.
o The queue is empty if front == rear.
 isFull(): Returns true if the queue is full.
o The queue is full if (rear + 1) % size == front.
Queue with Linked List
EXERCISES:

Q1. Given one stack with n elements, separate out even values in one stack and odd values in
another stack.

Q2. You are building an expression evaluator as part of a simple calculator application. Your
task is to implement
o infix_to_postfix
o Modify the infix_to_postfix algorithm to implement infix_to_prefix, include
comments where the code is modified.
Test with the given expressions: K+L-M*N+(O^P)*W/U/V*T+Q

Q3.
a) You are tasked with creating a ticketing system for a public transport service using a
linear queue implemented with an array. The system allows passengers to queue up to
purchase tickets. Once a passenger purchases their ticket, they are removed from the
queue. The queue is configured to hold a maximum of 10 passengers at a time.
Implement the “Ticket Queue” class, add 10 passengers to the queue and then remove the
first 5 passengers. Now, attempt to add 5 more passengers to the queue, and observe the
behavior of the queue.

b) Suggest and implement a potential solution or modification to this linear queue


implementation to handle this issue more effectively.

c) Implement (a) with the linked list.

Q4. We are given a stack data structure with push and pop operations, the task is to implement a
queue using instances of stack data structure and operations on them. (HINT: Two stacks will be
used either for enqueue or for dequeue)

Q5. Consider a rat placed at (0, 0) in a square matrix mat of order n* n. It has to reach the
destination at (n - 1, n - 1). Find all possible paths that the rat can take to reach from source to
destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R'
(right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it
while value 1 at a cell in the matrix represents that rat can be travel through it.
Input: mat[][] = [[1, 0, 0, 0], Output: DDRDRR DRDDRR

[1, 1, 0, 1],

[1, 1, 0, 0],

[0, 1, 1, 1]]
Q6. A two dimensional array of characters can be considered as a field. Each cell is either water
'W' or a tree 'T'. A forest is a collection of connected trees. Two trees are connected if they share
a side i.e. if they are adjacent to each other with respect to any of the four sides. Given the
information about the field, write a function which inputs this 2-D array and returns the size of
the largest forest, where size of a forest is the number of trees in it.

Input: Output: 10 z

You might also like