0% found this document useful (0 votes)
13 views78 pages

24CS201 DS Notes Unit 2

Uploaded by

deepikarn2020
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)
13 views78 pages

24CS201 DS Notes Unit 2

Uploaded by

deepikarn2020
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/ 78

1

2
Please read this disclaimer before proceeding:

This document is confidential and intended solely for the educational purpose of RMK
Group of Educational Institutions. If you have received this document through email in
error, please notify the system manager. This document contains proprietary information
and is intended only to the respective group / learning community as intended. If you
are not the addressee you should not disseminate, distribute or copy through e-mail.
Please notify the sender immediately by e-mail if you have received this document by
mistake and delete this document from your system. If you are not the intended
recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.
24CS201 Data Structures
(Lab Integrated)
Department : CSE,IT,ADS,CSBS,CSD

Batch / Year : 2024 – 2028 / I

Date : 20.1.2025

Created by : Subject handling faculty


members
1. CONTENTS
Page
S. No. Contents
No
1 Contents 5

2 Course Objectives 6

3 Pre Requisites 7

4 Syllabus 8

5 Course outcomes 11

6 CO- PO/PSO Mapping 12

7 Lecture Plan 13

8 Activity based learning 14


9 Lecture Notes 16
10 Assignments 51

11 Part A Questions & Answers 52

12 Part B Questions 56

13 Supportive online Certification 57


courses
14 Real time Applications 58

15 Contents beyond the Syllabus 61

16 Assessment Schedule 62

17 Prescribed Text Books & Reference 63


Books
18 Mini Project Suggestions 64

5
2. COURSE OBJECTIVES
To understand the concepts of List ADTs.

To learn linear data structures – stacks and queues ADTs.

To understand and apply Tree data structures

To understand and apply Graph structures

To analyze sorting, searching and hashing algorithms

6
3. PRE REQUISITES

• Pre-requisite Chart

24CS201 – DATA STRUCTURES

24CS101 – PROGRAMMING IN C++

7
4. SYLLABUS
DATA STRUCTURES L T P C
24CS201
(Common CSE,IT,ADS,CSBS,CSD) 3 0 3 4.5
OBJECTIVES:

The Course will enable learners to:


v To understand the concepts of List ADTs
v To learn linear data structures – stacks and queues
v To understand and apply Tree data structures
v To understand and apply Graph structures
v To analyze sorting, searching and hashing algorithms

UNIT I LINEAR DATA STRUCTURES – LIST 9+9


Algorithm analysis - running time calculations - Abstract Data Types (ADTs) – List ADT –
array- based implementation – linked list implementation – singly linked lists - circularly
linked lists - doubly-linked lists – applications of lists – Polynomial Manipulation – All
operations (Insertion, Deletion, Merge, Traversal).
List of Exercise/Experiments:
1. Array implementation of List ADTs.
2. Linked list implementation of List ADTs.

UNIT II LINEAR DATA STRUCTURES – STACKS, QUEUES 9+9


Stack ADT – Stack Model - Implementations: Array and Linked list - Applications - Balancing
symbols - Evaluating arithmetic expressions - Conversion of Infix to postfix expression -
Queue ADT – Queue Model - Implementations: Array and Linked list - applications of queues
- Priority Queues – Binary Heap – Applications of Priority Queues.
List of Exercise/Experiments:
1. Array implementation of Stack and Queue ADTs.
2. Linked list implementation of Stack and Queue ADTs.
3. Applications of List – Polynomial manipulations
4. Applications of Stack – Infix to postfix conversion and expression evaluation.
UNIT III NON LINEAR DATA STRUCTURES-TREES 9+9
Tree ADT – tree traversals - Binary Tree ADT – expression trees
– applications of trees – binary search tree ADT– AVL Tree.
SYLLABUS Contd...
List of Exercise/Experiments:
1. Implementation of Binary Trees and operations of Binary Trees.
2. Implementation of Binary Search Trees.
3. Implementation of Heaps using Priority Queues.

UNIT IV NON LINEAR DATA STRUCTURES - GRAPHS 9+9

Definition – Representation of Graph – Types of graph - Breadth-first traversal - Depthfirst


traversal – Topological Sort – Applications of graphs – BiConnectivity – Euler circuits.
List of Exercise/Experiments:
1. Graph representation and Traversal algorithms.

9+9
UNIT V SEARCHING, SORTING AND HASHING TECHNIQUES

Searching- Linear Search - Binary Search - Sorting - Bubble sort - Selection sort - Insertion
sort – Hashing - Hash Functions – Separate Chaining – Open Addressing – Rehashing –
Extendible Hashing.
List of Exercise/Experiments:
1. Implement searching and sorting algorithms.
TOTAL: 45 (L) + 45 (P) = 90 PERIODS
OUTCOMES:
Upon completion of the course, the students will be able to:
CO1: Analyze algorithms and abstract data types (ADTs).

CO2: Evaluate fundamental data structures.

CO3: Implement linked data structures and its application.


CO4: Apply advanced tree data structures.
CO5: Understand basic graph theory concepts.
CO6: Evaluate various searching and sorting algorithms.

TEXT BOOKS:
1. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C++”, 4th Edition, Pearson
Education, 2014.
2. SartajSahni, “Data Structures, Algorithms and Applications in C++”, Silicon paper
publications, 2004.

REFERENCES:
1. Rajesh K. Shukla, “Data Structures using C and C++”, Wiley India Publications, 2009.
2. NarasimhaKarumanchi, “Data Structure and Algorithmic Thinking with Python: Data
Structure and Algorithmic Puzzles”, CareerMonk Publications, 2020.
3. Jean-Paul Tremblay and Paul Sorenson, “An Introduction to Data Structures with
Application”, McGraw-Hill, 2017.
4. Mark Allen Weiss, “Data Structures and Algorithm Analysis in Java”, Third Edition, Pearson
Education, 2012.
5. Ellis Horowitz, SartajSahni, Susan Anderson-Freed, “Fundamentals of Data Structures in
C”, Second Edition, University Press, 2008.
6. Ellis Horowitz, SartajSahni, Dinesh P Mehta, “Fundamentals of Data Structures in C++”,
Second Edition, Silicon Press, 2007.
7. https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_013501578165051392
10584/overview

LIST OF EQUIPMENTS:
1. Standalone desktops with C/C++ compiler (or) Server with C/C++ compiler.
5. COURSE OUTCOMES
Upon completion of the course, the students will be able to:

COURSE OUTCOMES HKL

CO1 Analyze algorithms and abstract data types (ADTs). K3

CO2 Evaluate fundamental data structures.


K3

CO3 Implement linked data structures and its


K3
application.

CO4 Apply advanced tree data structures.


K3

CO5 Understand basic graph theory concepts. K3

CO6 Evaluate various searching and sorting algorithms. K2

HKL = Highest Knowledge Level

11
6. CO-PO/PSO Mapping

PROGRAM OUTCOMES PSO


CO PO PO PO PO PO PO PO PO PO PO PO PO P P P
S S S
1 2 3 4 5 6 7 8 9 10 11 12 O O O
1 2 3
CO1 3 3 3 1 1 - - - 2 1 - 1 - - -

CO2 3 2 3 1 2 - - - 2 1 - 1 - - -

CO3 3 3 3 1 2 - - 1 2 1 - 1 - - -

CO4 3 3 3 1 2 - - - 2 1 - 1 - - -

CO5 3 3 3 1 2 - - 1 2 1 - 1 - - -

CO6 2 3 3 - 3 - - 1 2 2 - 3 - - -

Correlation Level
1. Slight (Low)
2. Moderate (Medium)
3. Substantial (High) ,
If there is no correlation, put “-“.

12
7. LECTURE PLAN
Sl. Taxon
No. of. Proposed Actual Pertaining Mode of
No Topics o my
. Periods Date Date CO Delivery
Level

Stack ADT, Model As per


MD 1,
1 1 calender K3 MD 4
CO2, CO6
Stack –
As per CO2
Implementation MD 1,
2 1 calender K3 MD 4
using Array and
Linked List
MD 1,
3 Applications – 1 As per CO2, CO6 K2 MD 4
Balancing calender
Symbols

Applications –
As per CO2
Evaluating MD 1,
4 1 calender K3 MD 4
arithmetic
expressions
Conversion of
As per CO2
Infix to MD 1,
5 1 calender K2 MD 4
postfix
expression
Queue ADT – As per CO2
Model - MD 1,
6 1 calender K3 MD 4
Implementation
using Array and
Linked List
As per CO2 MD 1,
applications of
7 1 calender K3 MD 4
queues

As per CO2 MD 1,
8 Priority Queue 1 calender K2 MD 4

As per CO2 MD 1,
9 Binary Heap 1 calender K3 MD 4

CO2
As per
10 Applications of MD 1,
calender
Priority Queues. 1 K2 MD 4

CO2 K2 Code
11 As per
Lab Exercises 4 tantra
-14 calender

* MD1 – Oral Presentation


* MD 4 – Hands on using any IDE
8. Activity Based Learning
Common Activities

Learning Methods Activities

Class Exercises, Challenge Yourself, Practice


Learn by Solving Problems at Home exercises posted in Code Tantra
Portal

Learn by Questioning Knowledge Check / MCQ Using Code Tantra


portal and RMK Nextgen App

Learn by Hands on Practice programs and Home work programs


available in Code Tantra Portal
8. Activity Based Learning

CLASSROOM ACTIVITY-1
TITLE: TOWER OF HANOI PROBLEM FOR (N=3)
METHODOLOGY:
Z to A approach is an innovative technique which explains application of particular
concept first and the concept itself later. So, this innovative method, called Z to A
technique can be used in teaching the concept of Stack in data structure more
effectively.
A stack is a freshly-opened pack of biscuits. You take first the last one that went in
the box. By the time you get to the last one you realize that this biscuit was the first
to be put in the box.
PROCEDURE OF CONDUCTING THE ACTIVITY:
First of all, one of the student stated the tower of Hanoi problem
and solved the same for N=3on black board.
Three students of different height played the role of different
diameters.
Some students instructed the movement of the three students playing
the role of disks.

15
8. Activity Based Learning
First three rows in the class were used as Peg A, Peg B and Peg C
between which these students (disks) were moved (from one peg to
the other) so that no student having higher height comes in front of
a lower height student.
The instructors told the three students to move according to the
steps/moves drawn on the black board (solved on board).
It involved 7 moves to solve the tower of Hanoi problem using
students as three disks.
At the end students and faculty both discussed that how ‘stack-data
structure’ is being used in the whole activity.
THE RESULT AND ANALYSIS:
Students found it more interesting to learn tower of Hanoi problem
through activity. They asked to explain more topics through activities. They
were more attentive during the activity than normal routine lecture.

CLASSROOM ACTIVITY-2
Queue : Grocery Checkout Game

Goal: Differentiate between simple, circular, and priority queues.


Activity:
• Set up a mock grocery checkout system.
• Use colored cards to represent customers with different priorities (e.g., green for
regular, red for VIP).
• Regular customers enter a simple or circular queue.
• VIP customers are placed in a priority queue and served first.
• Students simulate enqueuing and dequeuing operations while maintaining the
rules of each type of queue.
Learning Outcome:
Students understand different queue implementations and their uses.

16
9. LECTURE NOTES

Unit II

LINEAR DATA STRUCTURES –


STACKS, QUEUES

18
STACK ADT

Stack Definition:
A stack is a list with the restriction that inserts and deletes can be performed in only
one position, namely the end of the list called the top. Stacks are known as LIFO(Last
In First Out) lists.

A Stack of Books A Stack of Coins A Stack of Plates

Fig 2.1. Real Life Examples of Stack

Operations on Stack:

There are two basic operations on a stack :


PUSH – This operation is used to insert an element on to the stack.
POP – This operation is used to delete the most recently inserted element.
As shown in Fig 2.2, input to a stack is by the PUSH operation and output from a stack
is by the POP operation. The most recently inserted element is pointed to by top.

Fig 2.2. Stack Model


top

Fig 2.3. Push and Pop Demonstration

In the above Fig 2.3, assume the stack contains the following elements 10,20,30 and top
points to the topmost element 30.

Push(40,S) will insert 40 into the stack in the position pointed to by top and top will now
point to 40.

Pop(S) will remove the most recently inserted element (i.e) 40 from the stack as shown in Fig
2.3.

IMPLEMENTATION OF STACK
Stacks can be implemented using arrays as well as linked lists.
Array Implementation of Stack
In order to make manipulations in a stack, there are certain operations provided to us.

push() to insert an element into the stack

pop() to remove an element from the stack

top() Returns the top element of the stack.

isEmpty() returns true if stack is empty else false.

size()
Adding an element onto the stack (push operation)
Adding an element into the top of the stack is referred to as push operation. Push operation
involves following two steps.

• Increment the variable Top so that it can now referred to the next memory location.

• Add element at the position of incremented top. This is referred to as adding new element at
the top of the stack.

Stack is over flown when we try to insert an element into a completely filled stack therefore,
our main function must always avoid stack overflow condition.

void push(int val)

if(top>=n-1)

cout<<"Stack Overflow"<<endl;

else

top++;

stack[top]=val;

Implementation of POP algorithm using C++ language

Removing a data element from the stack data structure is called a pop operation. The pop
operation has two following steps:

• The value of the top variable will be incremented by one whenever you delete an item from
the stack.

• The topmost variable of the stack is stored in another variable, and then the value of the top
variable will be decremented by one.

• The pop operation returns the deleted element that was stored in another variable as a
result.
Stack data structure states an underflow condition when you try to delete a data element
when the stack is already empty.

void pop()

if(top<=-1)

cout<<"Stack Underflow"<<endl;

else

cout<<"The popped element is "<< stack[top] <<endl;

top--;

Routine to return isEmpty

void isEmpty()

if(top ==-1)

cout << "Stack empty \n";

} else

cout << "Stack not empty \n";

}
Routine to return isFull

void isFull()

if(top == n-1)

cout << "Stack Full \n";

} else

cout << "Stack not Full \n";

}
Routine to return top of stack

Display operations involve returning the topmost data element of the stack without
removing it from the stack.

Underflow conditions may occur if you try to return the topmost element if the stack is
already empty.

void display()

if(top>=0)

cout<<"Stack elements are:";

for(int i=top; i>=0; i--)

cout<<stack[i]<<" ";

cout<<endl;

}else

cout<<"Stack is empty";

}
Example:

Write a program to implement a stack for character conversion such that the
lowercase characters are converted to uppercase and vice versa

#include <iostream>

#include <stack>

#include <cctype> // For character classification and conversion functions

using namespace std;

class CharStack {

private:

stack<char> stk; // STL stack to store characters

public:

// Push each character onto the stack

void push(char ch) {

stk.push(ch);

// Pop characters from the stack, convert case, and print the result

void convertAndDisplay() {

string result;

// Process all characters in the stack

while (!stk.empty()) {

char ch = stk.top(); // Get the top character

stk.pop(); // Remove the character from the stack

// Convert case and append to the result string

if (islower(ch)) {

result += toupper(ch);

} else if (isupper(ch)) {

result += tolower(ch);
} else {

result += ch; // Non-alphabetic characters remain unchanged

// Reverse the result string to maintain original order

reverse(result.begin(), result.end());

// Print the final converted string

cout << "Converted string: " << result << endl;

};

int main() {

CharStack charStack;

string input;

// Input the string

cout << "Enter a string: ";

getline(cin, input);

// Push each character onto the stack

for (char ch : input) {

charStack.push(ch);

// Convert and display the modified string

charStack.convertAndDisplay();

return 0;

}
Linked List Implementation of Stack
We implement a stack using a singly linked list with a header. A push operation is performed by
inserting at the front of the list and a pop operation is performed by deleting the element at the
front of the list. A top operation will return the element at the front of the list.

#include <stdlib.h>
This is the declaration of a new class type
#include <iostream>
StackNode.
using namespace std;
class StackNode {
data field in node is used to hold data inside the
public:
linked list.
int data; StackNode *next;
next field in node is used to keep the address of
};
next node.
class StackList {
Here, we are declaring a variable top to the
StackNode* top;
StackNode type and initializing it to NULL.
public: StackList() {
We also define functions.
top = NULL;}
void push(int element);
void push(int element);
void pop();
void pop();
void display();
void display();
};

void StackList::push(int x) {

StackNode* temp;

temp = new stack;

if(temp == NULL) {

cout << "Stack is overflow.\n";

} else {

temp -> data = x;

temp -> next = top;

top = temp;

cout << "Successfully pushed.\n";}

}
Explanation:

By using this code we are pushing given element into the stack.

• Create a new temporary StackNode variable temp.

• Allocate the dynamic memory for these StackNode variable temp.

• System successfully allocate (release) the heap memory for StackNode variable temp i.e.
7078

• 7078 == NULL

• Evaluates to false, the control enters into the else-block.

• Here, integer value x is stored in the data field of temp.

• Here, change the top to the next field of temp.

• Here, we change the top pointer point to temporary variable temp.

void StackList::pop() {

StackNode* temp;

if(top == NULL) {

cout << "Stack is underflow.\n";

} else { temp = top; top = top -> next;

cout << "Popped value = " << temp -> data << "\n";

delete temp;}

Explanation:

By using this code we are popping the element from the stack.

• Here, we create a new temporary StackNode variable temp.

• 7059 == NULL

• Evaluates to false, the control enters into the else-block.

• Here, we point this temporary node temp to the top of the stack.

• Now point the top pointer to the next of the current top.

• Delete the temporary node using the delete() function.


void StackList::display() {

StackNode* temp = top;

if(temp == NULL) {

cout << "Stack is empty.";

} else {

cout << "Elements of the stack are : ";

while(temp != NULL) {

cout << temp -> data << " ";

temp = temp -> next; }

Explanation:

By using this code we are print the elements in the stack.

• Here, we create a new temporary StackNode variable temp and pointing to top.

i.e. temp = 7068

• 7068 == NULL

• Evaluates to false, the control enters into the else-block.This while-loop is repeated untill the
temp value is not NULL.

• It prints the data value of each member.

• Next traverse the temp to the next node.

Example:

#include<iostream>

using namespace std;

struct Node {

int data;

Node* next;

};
class Stack {

private:

Node* top;

public:

Stack() : top(nullptr) {}

void push(int value) {

Node* newNode = new Node();

newNode->data = value;

newNode->next = top;

top = newNode;

void pop() {

if (!isEmpty()) {

Node* temp = top;

top = top->next;

delete temp;

int peek() {

if (!isEmpty()) {

return top->data;

return -1;

bool isEmpty() {

return top == nullptr; }


void displayStack() {

if (isEmpty()) {

cout << "Empty" << endl;

return;

Node* current = top;

while (current != nullptr) {

cout << current->data;

if (current->next != nullptr) {

cout << "->";

current = current->next;

cout << endl;

};

int main() {

int n;

cin >> n;

Stack stack;

for (int i = 0; i < n; ++i) {

int operation;

cin >> operation;

if (operation == 1) {

int value;

cin >> value;


stack.push(value);

} else if (operation == 2) {

stack.pop();

} else if (operation == 3) {

cout << stack.peek() << endl;

stack.displayStack();

return 0;

Applications of Stack
1. Balancing Paranthesis ( Balancing Symbols)

2. Conversion of Infix Expression to Postfix Expression

3. Evaluation of Postfix Expression

4. Function Call

1. Balancing Symbols

Stacks can be used to check whether the parentheses in any algebraic expression are
balanced. An algebraic expression is valid if for every open bracket there is a corresponding
closing bracket.

Example

{( a + b ) * [( c + d )/e] }

The above expression is a valid expression as the parantheses are well balanced.

The expression {( a + b ) * ( c + d )/e] } is invalid as the the corresponding opening


bracket of ] is missing.
Algorithm:

1. Make an empty stack.

2. Read characters until end of file.

a. If the character is an open anything, push it onto the stack.

b. If it is a close anything, then

i. if the stack is empty report an error.

c. Otherwise, pop the stack.

d. If the symbol popped is not the corresponding opening symbol, then

report an error.

3. At end of file, if the stack is not empty report an error.

2. Conversion of Infix expression to Postfix expression


Algorithm:

1. Repeat until each character in the infix expression is scanned.

2. If an opening parenthesis like ( is encountered, push it on the stack .

3. If an operand (whether a digit or a character) is encountered, add it to the output ( postfix


expression).

4. If a closing parenthesis like ) is encountered, then

a. Repeatedly pop from stack and add it to the postfix expression until the corresponding
closing parenthesis ( is encountered.

b. Discard the opening parenthesis ( . (i.e) remove the ( from stack and do not add it to
the postfix expression

5. If an operator is encountered, then

a. Repeatedly pop from stack and add each operator (popped from the stack) to the
postfix expression which has the same precedence or a higher precedence than the
operator encountered.

b. Push the encountered operator to the stack

6. Repeatedly pop from the stack and add it to the postfix expression until the stack is empty.
Example:

Convert the following infix expression to postfix expression

[(a+b) *(c+d/f)] - g

Step 1: When [ is encountered , push it onto the stack

Stack Output

Step 2: When ( is encountered , push it onto the stack

Stack Output
Step 3: When a is encountered, it is an operand so display it on the output (postfix expression)

Stack Output

Step 4: When + is encountered, it is an operator so push it on to the stack.

Stack Output
Step 5: When b is encountered, it is an operand so display it on the output (postfix expression)

Stack Output

Step 6: When ) is encountered , pop the stack till corresponding ( and display all the symbols on
the output .

Stack Output

Step 7: When * is encountered, it is an operator so push it on to the stack.

Stack Output
Step 8: When ( is encountered, push it on to the stack.

Stack Output
Step 9: When c is encountered, it is an operand so display it on the output (postfix expression

Stack Output

Step 10: When + is encountered, it is an operator so push it on to the stack.

Stack Output
Step 11: When d is encountered, it is an operand so display it on the output (postfix
expression)

Stack Output
Step 12: When / is encountered, it is an operator so push it on to the stack.

Stack Output
Step 13: When f is encountered, it is an operand so display it on the output (postfix
expression)

Stack Output
Step 14: When ) is encountered, pop the stack till corresponding ( is seen on the stack and
display all the popped symbols on the output (postfix expression)

Stack Output
Step 15: When ] is encountered, pop the stack till corresponding [ is seen on the stack and
display all the popped symbols on the output (postfix expression)

Stack Output

Step 16: When - is encountered, it is an operator so push it on to the stack.

Stack Output
Step 17: When g is encountered, it is an operand so display it on the output (postfix
expression)

Stack Output
Step 18: We have reached the end of the infix expression, hence pop the stack till it becomes
empty and display the popped symbols on the output.

Stack Output

The resultant postfix expression is ab+cdf/+*g-

Program- Infix to postfix conversion

#include <iostream>

#include <stack>

#include <cctype>

using namespace std;

// Function to define precedence of operators

int precedence(char op) {

if (op == '^') return 3;

if (op == '*' || op == '/') return 2;

if (op == '+' || op == '-') return 1;

return 0;

}
// Function to check if the character is an operator

bool isOperator(char ch) {

return ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^';

// Function to convert infix to postfix

string infixToPostfix(const string& infix) {

stack<char> stk;

string postfix;

for (char ch : infix) {

// If the character is an operand, add it to the postfix expression

if (isalnum(ch)) {

postfix += ch;

// If the character is '(', push it to the stack

else if (ch == '(') {

stk.push(ch);

// If the character is ')', pop from the stack until '(' is found

else if (ch == ')') {

while (!stk.empty() && stk.top() != '(') {

postfix += stk.top();

stk.pop();

stk.pop(); // Pop '(' from the stack

}
// If the character is an operator

else if (isOperator(ch)) {

while (!stk.empty() && precedence(stk.top()) >= precedence(ch) && ch != '^') {

postfix += stk.top();

stk.pop();

stk.push(ch);

// Pop any remaining operators from the stack

while (!stk.empty()) {

postfix += stk.top();

stk.pop();

return postfix;

int main() {

string infix;

cout << "Enter an infix expression: ";

cin >> infix;

string postfix = infixToPostfix(infix);

cout << "The equivalent postfix expression is: " << postfix << endl;

return 0;

}
3. Evaluation of a Postfix Expression

Algorithm:

When a number is seen, it is pushed onto the stack.

1. When an operator is seen, the operator is applied to the two numbers (symbols) that are
popped from the stack and the result is pushed onto the stack.

Example:

Evaluate the following postfix expression

234*5+9/-

When 2,3,4 are encountered, they are pushed onto the stack.

The next symbol is *. It is an operator and hence two numbers are popped ( 3 and 4 ) from
the stack. The resultant 7 is pushed on to the stack.

The next symbol is 5 and therefore it is pushed on to the stack.


The next symbol is + . It is an operator and hence two numbers are popped ( 7 and 5 )
from the stack. The resultant 12 is pushed on to the stack.

The next symbol is 9 and therefore it is pushed on to the stack.

The next symbol is / . It is an operator and hence two numbers are popped ( 12 and 9 )
from the stack. The resultant 1.33 is pushed on to the stack.

The last symbol is - . It is an operator and hence two numbers are popped (2 and 1.33)
from the stack. The resultant 1.33 is pushed on to the stack.

The final answer is 0.67


4. Function Call

A recursive function is defined as a function that calls itself to solve a smaller version of its
task until a final call is made which does not require a call to itself. Since a recursive function
repeatedly calls itself, it makes use of the system stack to temporarily store the return
address and local variables of the calling function.When there is a function call, all the
important information that needs to be saved, such as register values and the return address
is saved (called as either an activation record or stack frame.

Example:

The program to find the factorial of a number is normally written using a recursive function.
Fig 2.4 shows how a stack is used to store the function calls. Once we reach the function call
where number is 1, the functions will be popped off from the stack one by one.

Fig 2.4. Call Stack for recursive function to find factorial of a number
Queue ADT
A queue is an ordered collection of items where insertion is done at a end called the rear and
deletion is done at the other end called front.

Delete Insert

Front Rear

Fig 2.5:Queue ADT

Like stacks, queues are also lists, where insertion is done at one end and deletion is performed
at the other end.

The technique or discipline followed by queue is FIFO(First In First Out)

The first element inserted in the queue will be the first element to be deleted.

The primitive operations of queue are

enqueue: inserts an element at the end of the list called rear end.

dequeue: deletes the element at the start of the list called the front end.
dequeue(Q) enqueue(x,Q)
Queue Q

Fig 2.6. Abstract model of a queue

Enqueue(insertion)

1) Elements are inserted at the rear portion of queue.

2) If the queue is full no more elements can be inserted resulting in overflow condition.

3)If the queue is not full then the rear pointer is incremented and the item is inserted.
-1 0 1 2 3 4

q 10 20 30 n=5

front rear

Fig 2.7 : Enqueue operation in queue


Queue Implementation using Array
Routine to perform enqueue operation

void enqueue() {

if(rear>=n-1)

cout<<“Queue overflow!”<<endl;

else

cout<<“enter the element to insert”<<endl;

cin>>item;

rear++;

q[rear]=item;

if(front==-1)

front=0;

Dequeue(deletion)
Elements are deleted from the front

1) If the queue is empty it results in underflow condition

2) If the queue is not empty , delete the element from front.

-1 0 1 2 3 4

q 0 20 30 n=5

front rear

Fig 2.8 : dequeue operation in queue


Routine to perform dequeue operation

void dequeue() {

if(rear==-1 || front > rear)

cout<<“Queue underflow”<<endl;

else

item=q[front];

front++;

cout<<“The deleted element is”<<item<<endl;

} }

Routine to display the elements of the queue

Check for queue empty condition .

If the queue is not empty print the elements from front to rear.

void display() {

if(rear==-1 || front > rear)

cout<<“Queue empty”<<endl;

else

for(i=front; i<= rear; i++)

cout<<q[i]<<endl;

} }
Implementation of Queue ADT using Linked List

A queue is an ordered collection of items where insertion is done at a end called the rear and

deletion is done at the other end called front.

The technique or discipline followed by queue is FIFO(First In First Out)

The first element inserted in the queue will be the first element to be deleted.

The primitive operations of queue are

enqueue: inserts an element at the end of the list called rear end.

dequeue: deletes the element at the start of the list called the front end.

dequeue(Q) enqueue(x,Q)
Queue Q

Fig 2.9 Abstract model of a queue

Linked list implementation of Queue

Declaring a queue node

Declares a node with 2 fields

1) Data

2) Pointer to next node

class QueueNode {

public :

int data;

QueueNode *next;

};
class QueueList {

QueueNode * front , * rear;

public :

QueueList() {

front = NULL;

rear = NULL;

This is the declaration of a new class QueueList.

Here, we are declaring two variables front, rear of type QueueNode.

we also declare a public constructor in which we initialize front and rear with NULL,
value.
Enqueue(insertion)
Inserts an element to the rear end of the queue

Eg
Q 10 20

rear
Q 10 20

30

rear
tmpcell

Fig 2.10 : Enqueue the element 30

If Q is empty , the new node will be inserted after Q.

Otherwise a rear pointer will be assigned to the last node in Q and the new node will be inserted
to rear.

Routine to enqueue an element in a Queue

void enqueue( elementtype X, Queue Q)

node_ptr tmpcell , rear;

tmpcell=malloc(sizeof(struct node)); tmpcell->element=X;

if(Q->next==NULL)

tmpcell->next=Q->next; Q->next=tmpcell;

else {

rear =Q->next;

while(rear->next!=NULL)

rear=rear->next;

tmpcell->next=rear->next; rear->next=tmpcell; } }
dequeue(deletion)

deletes an element from the front end of the queue

Eg
Q 10 20

front

Q 20

Fig 2.11 : dequeue the element 10

If Q->next ==NULL then display Queue empty. Otherwise assign the next node after the
header node as front and delete that node.

Routine to dequeue an element from Queue

void deque(Queue Q) {

node_ptr front;

if (Q->next==NULL)

cout<<“Queue is empty”<<endl;

else {

front=Q->next;

Q->next=front->next;

free(front); } }

Applications of Queue
Task Scheduling: Queues can be used to schedule tasks based on priority or the order in
which they were received.

Resource Allocation: Queues can be used to manage and allocate resources, such as
printers or CPU processing time.
• Batch Processing: Queues can be used to handle batch processing jobs, such as data analysis
or image rendering.

• Message Buffering: Queues can be used to buffer messages in communication systems, such as
message queues in messaging systems or buffers in computer networks.

• Event Handling: Queues can be used to handle events in event-driven systems, such as GUI
applications or simulation systems.

• Traffic Management: Queues can be used to manage traffic flow in transportation systems, such
as airport control systems or road networks.

PRIORITY QUEUE
Priority queue are special kind of queue, where each element has a priority associated with it as
shown in the Fig 2.14.

deletemin insert
Priority Queue

Fig 2.14: Priority Queue

It is a data structure which determines the priority of jobs.

 The Minimum the value of priority, higher is the priority of the job.

 The best way to implement the priority queue is Binary Heap.

Implementation of Priority Queue:

It can be implemented in three ways.


1. Linked List

2. Binary search Tree


3. Binary Heap
 Priority Queue is an extension of the queue with the following properties:

 Every item has a priority associated with it.

 An element with high priority is dequeued before an element with low priority.

 If two elements have the same priority, they are served according to their order in the queue.

 A Binary Heap is a Binary Tree with the following properties:

 It is a Complete Tree. This property of Binary Heap makes them suitable to be stored in an
array.

 A Binary Heap is either Min Heap or Max Heap.

 In a Min Binary Heap, the key at the root must be minimum among all keys present in Binary
Heap. The same property must be recursively true for all nodes in Binary Tree.

 Similarly, in a Max Binary Heap, the key at the root must be maximum among all keys present
in Binary Heap. The same property must be recursively true for all nodes in Binary Tree.

 Example of A Binary Max Heap

 Suppose below is the given Binary Heap that follows all the properties of Binary Max Heap.

 Now a node with value 32 need to be insert in the above heap: To insert an element, attach
the new element to any leaf. For Example A node with priority 32 can be added to the leaf of
the node 7. But this violates the heap property. To maintain the heap property, shift up the
new node 32.
 Shift Up Operation get node with 32 at the correct position: Swap the incorrectly placed node
with its parent until the heap property is satisfied. For Example: As node 7 is less than
node 32 so, swap node 7 and node 32. Then, swap node 31 and node 32.

 ExtractMax: The maximum value is stored at the root of the tree. But the root of the tree
cannot be directly removed. First, it is replaced with any one of the leaves and then
removed. For Example: To remove Node 45, it is first replaced with node 7. But this violates
the heap property, so move the replaced node down. For that, use shift-down operation.
ShiftDown operation: Swap the incorrectly placed node with a larger child until the heap
property is satisfied. For Example Node 7 is swapped with node 32 then, last it is swapped
with node 31.

ChangePriority: Let the changed element shift up or down depending on whether its priority
decreased or increased. For Example: Change the priority of nodes 11 to 35, due to this
change the node has to shift up the node in order to maintain the heap property.

52
Remove: To remove an element, change its priority to a value larger than the
current maximum, then shift it up, and then extract it using extract max. Find the
current maximum using getMax.

GetMax: The max value is stored at the root of the tree. To getmax, just return the
value at the root of the tree.

Array Representation of Binary Heap

Since the heap is maintained in form of a complete binary tree, because of this fact
the heap can be represented in the form of an array. To keep the tree complete and
shallow, while inserting a new element insert it in the leftmost vacant position in the
last level i.e., at the end of our array. Similarly, while extracting maximum replace
the root with the last leaf at the last level i.e., the last element of the array. Below is
the illustration of the same:

53
#include <bits/stdc++.h>

using namespace std;

int H[50];

int size = -1;

// Function to return the index of the

// parent node of a given node

int parent(int i)

return (i - 1) / 2;

// Function to return the index of the

// left child of the given node

int leftChild(int i)

return ((2 * i) + 1);

// Function to return the index of the

// right child of the given node

int rightChild(int i)

return ((2 * i) + 2);

54
// Function to shift up the node in order

// to maintain the heap property

void shiftUp(int i)

while (i > 0 && H[parent(i)] < H[i]) {

// Swap parent and current node

swap(H[parent(i)], H[i]);

// Update i to parent of i

i = parent(i);

// Function to shift down the node in

// order to maintain the heap property

void shiftDown(int i)

int maxIndex = i;

// Left Child

int l = leftChild(i);

if (l <= size && H[l] > H[maxIndex]) {

maxIndex = l;

} // Right Child

int r = rightChild(i);

if (r <= size && H[r] > H[maxIndex]) {

maxIndex = r;

}
55
// If i not same as maxIndex

if (i != maxIndex) {

swap(H[i], H[maxIndex]);

shiftDown(maxIndex);

// Function to insert a new element

// in the Binary Heap

void insert(int p)

size = size + 1;

H[size] = p;

// Shift Up to maintain heap property

shiftUp(size);

// Function to extract the element with

// maximum priority

int extractMax()

int result = H[0];

// Replace the value at the root

// with the last leaf

H[0] = H[size];

size = size - 1;

56
// Shift down the replaced element

// to maintain the heap property

shiftDown(0);

return result;

// Function to change the priority

// of an element

void changePriority(int i, int p)

int oldp = H[i];

H[i] = p;

if (p > oldp) {

shiftUp(i);

else {

shiftDown(i);

// Function to get value of the current

// maximum element

int getMax()

return H[0];

}
57
// Function to remove the element

// located at given index

void remove(int i)

H[i] = getMax() + 1;

// Shift the node to the root

// of the heap

shiftUp(i);

// Extract the node

extractMax();

// Driver Code

int main()

/* 45

/ \

31 14

/ \ / \

13 20 7 11

/ \

12 7

Create a priority queue shown in

example in a binary max heap form.

Queue will be represented in the

form of array as:


58
45 31 14 13 20 7 11 12 7 */
// Insert the element to the priority queue

insert(45);

insert(20);

insert(14);

insert(12);

insert(31);

insert(7);

insert(11);

insert(13);

insert(7);

int i = 0;

// Priority queue before extracting max

cout << "Priority Queue : ";

while (i <= size) {

cout << H[i] << " ";

i++;

Applications of Priority queue

• Dijkstra’s Shortest Path Algorithm using priority queue: When the graph is stored in
the form of adjacency list or matrix, priority queue can be used to extract minimum
efficiently when implementing Dijkstra’s algorithm.

• Prim’s algorithm: It is used to implement Prim’s Algorithm to store keys of nodes


and extract minimum key node at every step. Data Compression: It is used
in Huffman codes which is used to compresses data.

• Artificial Intelligence : A * Search Algorithm : The A* search algorithm finds the


shortest path between two vertices of a weighted graph, trying out the most
promising routes first. 59
• The priority queue (also known as the fringe) is used to keep track of unexplored routes, the
one for which a lower bound on the total path length is smallest is given highest priority.

• Heap Sort : Heap sort is typically implemented using Heap which is an implementation of
Priority Queue.

• Operating systems: It is also used in Operating System for load balancing (load balancing on
server),0 interrupt handling.

• Optimization problems: Priority Queue is used in optimization problems such as Huffman


coding, Kruskal’s Algorithm and Prim’s Algorithm

• Robotics: Priority Queue is used in robotics to plan and execute tasks in a priority-based
manner.

• Event-driven simulations: Priority queues are used in event-driven simulations, such as


network simulations, to determine which events should be processed next.

• Medical systems: Priority queues are used in medical systems, such as triage systems in
emergency departments, to prioritize patients based on the urgency of their condition.

60
ONLINE LEARNING

S.No Topic Link


https://people.ok.ubc.ca/ylucet/DS/StackArray.
1 Stack using Array html
Stack using Linked https://people.ok.ubc.ca/ylucet/DS/StackLL.ht
2 ml
list
http://ksuweb.kennesaw.edu/faculty/rbrow21
1/web_lectures/postfix/
3 Infix to Postfix https://www.mathblog.dk/tools/infix-postfix-
Conversion converter/
Evaluation of Postfix https://www.ideserve.co.in/learn/postfix-
4 expression-evaluation#algorithmVisualization
expression
https://people.ok.ubc.ca/ylucet/DS/QueueArra
5 Queue using Array y.html
Queue Using Linked https://people.ok.ubc.ca/ylucet/DS/QueueLL.h
6 tml
list
http://littlesvr.ca/dsa-html5-
7 Circular Queue animations/cyclicqueue.php

61
10. ASSIGNMENT : UNIT – II
(CO2, K4)
1. Implement the stack data structure. You must implement the class edu.iitd.col1062020.

MyStack<T> with the following methods. It must be a generic class (i.e. you can specify the
data type while creating the object). You are being provided the Interface with signatures of
the functions and you need to complete the code to implement the desired functionality.

MyStack():Constructor for MyStack class. Initialize an empty array of type.

void push(T value):Insert the value at the top of the stack. Resize if the internal array is full.

T pop() throws edu.iitd.col1062020.EmptyStackException: Delete the top element of the stack,


and return it. If the stack is empty, you must throw the specified exception.

T top() throws edu.iitd.col1062020.EmptyStackException: Return the top element of the stack.


If the stack is empty, you must throw the specified exception.

boolean isEmpty(): Returns true if the stack is empty, false otherwise.


2. Given a stack, sort it using recursion. Use of any loop constructs like while, for etc. is not
allowed.
3. Check if a queue can be sorted into another queue using a stack
4. Given a Queue consisting of first n natural numbers (in random order). The task is to check
whether the given Queue elements can be arranged in increasing order in another Queue
using a stack. The operation allowed are:
1. Push and pop elements from the stack
2. Pop (Or enqueue) from the given Queue.
3. Push (Or Dequeue) in another Queue.
5. Given a queue of integers of even length, rearrange the elements by interleaving the first half
of the queue with the second half of the queue. Only a stack can be used as an auxiliary
space.
Input : 1 2 3 4
Output : 1 3 2 4

Input : 11 12 13 14 15 16 17 18 19 20
Output: 11 16 12 17 13 18 14 19 15 20
62
11. PART A : Q & A : UNIT – II
SN
Questions and Answers CO K
o

What is Stack?
A stack is a list with the restriction that inserts and deletes
1 K1
can be performed in only one position, namely the end of
the list called the top

List the operations performed on stack.


PUSH – This operation is used to insert an element on to the
2 stack. K1
POP – This operation is used to delete the most recently
inserted element.

What is the use top pointer?


3 It is used to indicate the top of the stack element. Used to K1
check whether stack isempty(if top==1) CO2

How did you check stack empty in linked stack?


int is_empty( STACK S )
4 { K2
return( S->next == NULL );
}

List the applications of stack.


1.Balancing Paranthesis
5 2.Conversion of Infix Expression to Postfix Expression K1
3.Evaluation of Postfix Expression
4.Function Call

63
11. PART A : Q & A : UNIT – II
SNo Questions and Answers CO K

Convert the infix expression x^y/(5*z)+2 to postfix


6 form. K2
The Postfix form is: xy^5z*/2+

What do you mean by Balancing Paranthesis?


An algebraic expression is valid if for every open bracket
7 K1
there is a corresponding closing bracket.
Example:{( a + b ) * [( c + d )/e] }

How to check the overflow condition in stack?


8 If the top pointer reaches the maximum size of the stack K2
then physically and logically the stack is full.

Why stack is called LIFO list?


The last element inserted into the stack is the first element CO2
9 K2
to be deleted. For this reason, stack is called Last-In First-
Out list.

What are the limitations in the stack, when array


used as home of stack?
The Array is finite collection of elements and in stack the
10 K1
number of elements is unlimited. As the stack dynamically
changes the attempts to insert more elements than the
array size cause overflow

What do you mean by multiple stack?


11 Multiple stacks are a special type of stack that have more K1
than one stack in the same array of sufficient size.

64
11. PART A : Q & A : UNIT – II
SNo Questions and Answers CO K

Define Queue ADT.


A queue is an ordered collection of items where insertion
is done at a end called the rear and deletion is done at
the other end called front. The technique or discipline
followed by queue is FIFO(First In First Out). The first
12 K1
element inserted in the queue will be the first element to
be deleted.
Dele Inse
te rt
Fron Rear
t

What are the operations performed on Queue?


The primitive operations of queue are enqueue and
dequeue. CO2
13 enqueue: inserts an element at the end of the list called K1
rear end.
dequeue: deletes the element at the start of the list called
the front en3

What is a circular queue? State its advantage over


linear queue.
The problem in the linear queue is that even when the
queue is not full, if the rear has reached to the end of the
14 K1
queue, no more elements can be inserted. The simple
solution is that whenever front or rear gets to the end of
the queue it is wrapped around to the beginning. This is
known as circular queue.

65
11. PART A : Q & A : UNIT – II
SNo Questions and Answers CO K

Draw the abstract model of Queue.


enqueue: inserts an element at the end of the list called
rear end.
15 dequeue: deletes the element at the start of the list called K1
the front end
dequeue(Q) enqueue(x,Q)
Queue Q

Define priority queue with diagram and list the


operations.
Priority queue are special kind of queue, where each
element has a priority associated with it. CO2

deletemin insert
16 K1
Priority Queue

Priority Queue
1. Insert : Enqueue the new item.
2. Deletemin: Dequeue the item with the highest priority.
3. Peek : Get the element at front of the queue

List the applications of priority queue.


• Prim's algorithm
17 • Dijkstra's shortest path algorithm K1
• A* Search algorithm
• Priority queues are used to sort heaps.

66
11. PART A : Q & A : UNIT – II
SNo Questions and Answers CO K

•Operating system for load balancing and interrupt


handling.
• Priority queues are used in Huffman codes for data
K1
compression.
• In traffic light, depending upon the traffic, the colors will
be given priority.

List out the different ways to implement the


priority queue.
It can be implemented in three ways.
18 K1
1. Linked List
2. Binary search Tree
3. Binary Heap
CO2
What is double ended queue?
In deque insertion and deletion operations are performed
at both ends of the Queue. Deque can bi implemented
using circular array.

Dele 0 1 2 3 4 5 Inse
19 tion rtion K1

Inse Dele
rtion Fro Re tion
nt ar

Double Ended Queue

67
11. PART A : Q & A : UNIT – II
SN
Questions and Answers CO K
o

List the operations of dequeue.


20 Insertfront(), Insertrear(), Deletefront(), Deleterear(), K1
Getfront(), Getrear(), Isempty(), Isfull(), Display()

. List down the applications of deque.


•Palindrome checker
21 K1
•Job scheduling algorithm for multiple processors.
•Undo-redo operations in software applications.

List down the exceptional conditions of deque.


(i) Input Restricted Deque
Here insertion is allowed at one end and deletion is allowed
22 at both ends. K1
(ii) Output Restricted deque CO2
Here insertion is allowed at both ends and deletion is
allowed at one end.

What is reverse polish expression?


It is a postfix expression in which the operators are
23 K1
preceded by operand.
Eg: AB+C*

Differentiate between stack and queue.

24 K2

68
12. PART B QUESTIONS : UNIT – II
(CO2, K2)

1. Explain in detail about stack and implement the same using array.

2. Explain in detail about stack and implement the same using linked list.

3. Discuss the various applications of stack with examples.

4. Write an algorithm to create two stacks using single array

5. Explain in detail the array based implementation of Queue ADT.

6. Explain in detail the linked list implementation of Queue ADT.

7. What is a circular queue? Write the procedure to insert an element to circular

queue and delete an element from a circular queue using array implementation?

8. Write functions to insert, deletemin and display a node from a priority queue.

PART C (CO2, K3)

1. There are ‘N’ number of balls in the box. The colors po the balls are red and blue.

You are requested to stack the balls in the bottom sealed basket one by one. The

order of placing the balls is two consecutive red balls followed by the two

consecutive blue balls. Later, create two empty queues Q1 and Q2. Remove the

last inserted ball from the basket and place it in Q1. Similarly remove the next ball

from the basket and insert in Q2. Develop a program to repeat this process untill

the basket is empty and also print the color of the balls in both the queues.

2. Write an algorithm to check whether given expression balanced or not and convert

the same in to its equivalent postfix form.

3. Convert the infix expression into postfix expression and evaluate the postfix

expression using stack

i) ((A-B)+C*D)/((E+F)-C)

ii) (300+23)*(43-21)/(84+7) [evaluate the postfix]


12. PART B QUESTIONS : UNIT – II

4. Check for balanced parentheses in an expression


5. Given an expression string exp, write a program to examine whether the pairs
and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.
6. Sort a stack using recursion
7. Interleave the first half of the queue with second half
13. SUPPORTIVE ONLINE
CERTIFICATION COURSES
UNITS : I TO V

COURSERA
DATA STRUCTURES
DATA STRUCTURES AND ALGORITHMS
DATA STRUCTURES AND PERFORMANCE
PYTHON DATA STRUCTURES

UDEMY
LEARNING DATA STRUCTURES IN C PROGRAMMING LANGUAGE
DATA STRUCTURES IN C LANGUAGE

NPTEL
PROGRAMMING, DATA STRUCTURES AND ALGORITHM USING PYTHON

71
14. REAL TIME APPLICATIONS :
UNIT – II
DAY TO DAY LIFE

STACK

Women’s Bangles: Women wear a bangle one by one and to pull the first one they
have to first pull out the last one.

Books and Clothes: Piled on top of each other is a great example of the stack.

Floors in a Building: If a person is living on the top floor and wants to go outside,
he/she first needs to land on the ground floor.

Browsers: Web browsers use the stack to keep track of the history of websites if
you click back then the previous site opens immediately.

INDUSTRY

Text editor

Your regular text editor has the functionality of editing and storing text while it is
being written or edited. So, there are multiple changes in the cursor position. To
achieve high efficiency, we require a fast data structure for insertion and modification.
And the ordinary character arrays take time for storing strings.

You can experiment with other data structures like gap buffers and ropes to solve
these issues. Your end objective will be to attain faster concatenation than the usual
strings by occupying smaller contiguous memory space.

72
15. CONTENT BEYOND
SYLLABUS : UNIT – II
Backtracking using Stack

Backtracking is an algorithmic-technique for solving problems recursively by trying to build


a solution incrementally, one piece at a time, removing those solutions that fail to satisfy the
constraints of the problem at any point of time (by time, here, is referred to the time elapsed
till reaching any level of the search tree).

For example, consider the SudoKo solving Problem, we try filling digits one by one.
Whenever we find that current digit cannot lead to a solution, we remove it (backtrack) and
try next digit. This is better than naive approach (generating all possible combinations of
digits and then trying every combination one by one) as it drops a set of permutations
whenever it backtracks.

Example: Rat in a Maze

A Maze is given as N*N binary matrix of blocks where source block is the upper left most
block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A
rat starts from source and has to reach the destination.

The rat can move only in two directions: forward and down
In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in
the path from source to destination. Note that this is a simple version of the typical Maze
problem. For example, a more complex version can be that the rat can move in 4 directions
and a more complex version can be with a limited number of moves.

73
15. CONTENT BEYOND
SYLLABUS : UNIT – II

Initial maze Solution maze

Approach: Form a recursive function, which will follow a path and check if the
path reaches the destination or not. If the path does not reach the destination then
backtrack and try other paths.
Algorithm:
1. Create a solution matrix, initially filled with 0’s.
2. Create a recursive function, which takes initial matrix, output matrix and position of
rat (i, j).
3. if the position is out of the matrix or the position is not valid then return.
4. Mark the position output[i][j] as 1 and check if the current position is destination
or not. If destination is reached print the output matrix and return.
5. Recursively call for position (i+1, j) and (i, j+1).
6. Unmark position (i, j), i.e output[i][j] = 0.

Online References
https://www.geeksforgeeks.org/rat-in-a-maze-backtracking-2/
https://www.youtube.com/watch?v=xy0pIcoWCd0

74
16. ASSESSMENT SCHEDULE

Tentative schedule for the Assessment During 2024-2025 Even


semester

Name of
S.NO Start Date End Date Portion
the
Assessment
1 Unit Test 1 08.02.2025 15.02.2025 UNIT 1

2 IAT 1 24.02.2025 28.02.2025 UNIT 1 & 2

3 Unit Test 2 18.03.2025 22.03.2025 UNIT 3

4 IAT 2 01.04.2025 05.04.2025 UNIT 3 & 4

5 Model 28.04.2025 07.05.2025 ALL 5 UNITS

75
17. PRESCRIBED TEXT BOOKS &
REFERENCE BOOKS
TEXTBOOKS:
1. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C++”,
4th Edition, Pearson Education, 2014.
2. SartajSahni, “Data Structures, Algorithms and Applications in C++”,
Silicon paper publications, 2004.

REFERENCES:
1. Rajesh K. Shukla, “Data Structures using C and C++”, Wiley India
Publications, 2009.
2. NarasimhaKarumanchi, “Data Structure and Algorithmic Thinking
with Python: Data Structure and Algorithmic Puzzles”, CareerMonk
Publications, 2020.
3. Jean-Paul Tremblay and Paul Sorenson, “An Introduction to Data
Structures with Application”, McGraw-Hill, 2017.
4. Mark Allen Weiss, “Data Structures and Algorithm Analysis in Java”,
Third Edition, Pearson Education, 2012.
5. Ellis Horowitz, SartajSahni, Susan Anderson-Freed, “Fundamentals
of Data Structures in C”, Second Edition, University Press, 2008.
6. Ellis Horowitz, SartajSahni, Dinesh P Mehta, “Fundamentals of
Data Structures in C++”, Second Edition, Silicon Press, 2007.
7.https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth
_01350157816505139210584/overview

LIST OF EQUIPMENTS:
1. Systems with Linux/Ubuntu Operating System with gnu C++
compiler
76
18. MINI PROJECT SUGGESTION
Objective:
This module facilitate hands-on skills of the students (from the
practical courses more effectively) and they can try the following mini
projects for deep understanding in Data Structures.

Planning:
This method is mostly used to improve the ability of students in
application domain and also to reinforce knowledge imparted during the
lecture.
Being a technical institute, this method is extensively used to provide
empirical evidence of theory learnt.
Students are asked to prepare mini projects involving application of the
concepts, principles or laws learnt.
The faulty guides the students at various stages of developing the
project and gives timely inputs for the development of the model.

MPQ1
A linked list is a linear collection of data elements called nodes that
“point” to the next node by means of a pointer. Each node holds a single
element of data and a link or pointer to the next node in the list. A head
node is the first node in the list, a tail node is the last node in the list.
Below is a basic representation of a linked list:
[ NODE(head) ] -> [ NODE ] -> [ NODE(tail) ] -> nil

77
PROJECT DESCRIPTION
You will need two classes:
LinkedList class, which will represent the full list.
Node class, containing a #value method and a link to the #next_node, set both
as nil by default.
Build the following methods in your linked list class:
append(value) adds a new node containing value to the end of the list
prepend(value) adds a new node containing value to the start of the list
size returns the total number of nodes in the list
head returns the first node in the list
tail returns the last node in the list
at(index) returns the node at the given index
pop removes the last element from the list
contains(value) returns true if the passed in value is in the list and otherwise returns
false.
find(value) returns the index of the node containing value, or nil if not found.
to_s represent your LinkedList objects as strings, so you can print them out and
preview them in the console. The format should be: ( value ) -> ( value ) -> ( value )
-> nil

Extra Credit
insert_at(value, index) that inserts the node with the provided value at the given index
remove_at(index) that removes the node at the given index. (You will need to update
the links of your nodes in the list when you remove a node.)
Note: Language, Platform, are not specified and left open for student’s choice. All your
solutions can be put in your repository as well as in the below common repository,
https://github.com/Prathi22891/DS-projects

78

You might also like