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

Siddh Ds

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

Siddh Ds

siddf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

Degree Engineering

A Laboratory Manual for

Data Structures
(3130702)

Bachelor of Engineering in
Information and Communication Technology
[Semester - 3]

Enrolment No 230170132038
Name Patel siddh sunilkumar
Branch DATA SCIENCE
Academic Term 2024
Institute Name VISHWAKARMA GOVERNMENT
ENGINEERING COLLEGE

Directorate of Technical Education, Gandhinagar,


Gujarat
Vishwakarma Government Engineering College
Information and Communication Technology Department

CERTIFICATE

This is to certify that Mr./Ms. Patel siddh sunilkumar Enrollment No.

230170146053 of B.E. Semester - III from data science of this Institute (GTU Code:

017) has satisfactorily completed the Practical work for the subject Data structure

(3130702) for the academic year 2023-24.

Place: VGEC Chandkheda

Date: ___________

Signature of Course Faculty Head of the Department


Data Structure (3130702) 230170146053

Preface

Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant competencies
in psychomotor domain. By keeping in view, GTU has designed competency focused outcome-
based curriculum for engineering degree programs where sufficient weightage is given to
practical work. It shows importance of enhancement of skills amongst the students and it pays
attention to utilize every second of time allotted for practical amongst students, instructors and
faculty members to achieve relevant outcomes by performing the experiments rather than having
merely study type experiments. It is must for effective implementation of competency focused
outcome-based curriculum that every practical is keenly designed to serve as a tool to develop
and enhance relevant competency required by the various industry among every student. These
psychomotor skills are very difficult to develop through traditional chalk and board content
delivery method in the classroom. Accordingly, this lab manual is designed to focus on the
industry defined relevant outcomes, rather than old practice of conducting practical to prove
concept and theory.

By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each experiment
in this manual begins with competency, industry relevant skills, course outcomes as well as
practical outcomes (objectives). The students will also achieve safety and necessary precautions
to be taken while performing practical.

This manual also provides guidelines to faculty members to facilitate student centric lab activities
through each experiment by arranging and managing necessary resources in order that the
students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.

Data Structures is a core course in all computer science undergraduate curricula. The course is
the basis for understanding several data structures and also algorithms that operate on them. The
course forms the foundation for almost all computer science subjects: compilers, operating
systems, databases, AI and software engineering. The course comes with a lab in most universities
in India. The associated lab in university curricula focuses on implementation of algorithms
operating on the data structures, i.e., coding programs on the data structures and algorithms.
Data Structure (3130702) 230170146053

DTE’s Vision

▪ To provide globally competitive technical education


▪ Remove geographical imbalances and inconsistencies
▪ Develop student friendly resources with a special focus on girls’ education and support to
weaker sections
▪ Develop programs relevant to industry and create a vibrant pool of technical professionals

Institute’s Vision

To create an ecosystem for proliferation of socially responsible and technically sound engineers,
innovators and entrepreneurs.

Institute’s Mission

• To develop state-of-the-art laboratories and well-equipped academic


infrastructure.
• To motivate faculty and staff for qualification up-gradation, and
enhancement of subject knowledge.
• To promote research, innovation and real life problem solving skills.
• To strengthen linkages with industries, academic and research
organizations.
• To reinforce concern for sustainability, natural resource conservation and
social responsibility.

Department’s Vision

To equip students with the necessary skills in data science to become proficient professionals
capable of leveraging technology to deliver effective and sustainable solutions for real-world
challenges.

Department’s Mission

• To cultivate highly skilled data scientists who excel in technical proficiency while embodying
social responsibility.
• To establish state-of-the-art academic infrastructure and advanced facilities, dedicated to
providing comprehensive training in the field of data science for students.
• To foster collaborations with industry, government bodies, and research & development
institutes, aiming to enhance the professional growth of faculty and students.
• To leverage data science techniques to address challenges and solve problems pertinent to
both industry and society.
• To create an environment that supports both research and entrepreneurship.
Data Structure (3130702) 230170146053

Programme Outcomes (POs)

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change
Data Structure (3130702) 230170146053

Program Specific Outcomes (PSOs)

• Basic knowledge of Engineering including software and hardware which helps data scientist
to collect and preprocess data based on problem domain.

Program Educational Objectives (PEOs)

• Possess technical and research skill to solve problems faced by industry and society using
data science techniques.
• Acquire basic engineering, design, analysis, implementation and testing skills which help
them to solve real life problem of industry and society.
• Shows professionalism in the field of data science by acquiring skills for research,
entrepreneurship and higher study.
• To be employable by keeping pace with frequently changing technology using lifelong
learning skill.
• To showcase professionalism at workplace and social life by being supportive and having
legal and ethical responsibilities.
Data Structure (3130702) 230170146053

Practical – Course Outcome matrix

Course Outcomes (COs)


Define and classify various data structures, storage structures and
CO_3130702.1
common operations on them
Create various linear data structures with their representation and
CO_3130702.2
perform different operations on them
Create various nonlinear data structures with their representation and
CO_3130702.3
perform different operations on them
CO_3130702.4 Apply various searching sorting techniques on data set
Solve the given a problem using an appropriate data structure to achieve
CO_3130702.5 optimal performance and compare its performance with other possible
data structures

Sr. CO CO CO CO CO
Practical Outcome/Title of experiment
No. 1 2 3 4 5

1. Classification of Data Structure and Stack

1.1 Classify various data structures


1.2 Implement a program for stack that performs
following operations using array. (a) PUSH (b) POP
(c) PEEP (d) CHANGE (e) DISPLAY
1.3 Implement a program to convert infix notation to
√ √ √
postfix notation using stack.
1.4 Write a program to implement Tower of Hanoi
problem.
1.5 Identify widely used application which use stack data
structure for implementation of its important feature.

2. Queue

2.1 Write a program to implement QUEUE using arrays


that performs following operations (a) INSERT (b)
DELETE (c) DISPLAY
2.2 Write a program to implement Circular Queue using
arrays that performs following operations. (a) √ √
INSERT (b) DELETE (c) DISPLAY
2.3 Identify widely used application which use Queue
data structure for implementation of its important
feature.

3. Singly linked list

3.1 Write a menu driven program to implement


following operations on the singly linked list. √ √
(a) Insert a node at the front of the linked list.
Data Structure (3130702) 230170146053

(b) Insert a node at the end of the linked list.


(c) Insert a node such that linked list is in ascending
order.(according to info. Field)
(d) Delete a first node of the linked list.
(e) Delete a node before specified position.
(f) Delete a node after specified position.
3.2 Write a program to implement stack using linked list.
3.3 Write a program to implement queue using linked
list.

4. Doubly linked list

4.1 Write a program to implement following operations


on the doubly linked list.
(a) Insert a node at the front of the linked list.
√ √
(b) Insert a node at the end of the linked list.
(c) Delete a last node of the linked list.
(d) Delete a node before specified position.

5. Circular linked list

5.1 Write a program to implement following operations


on the circular linked list.
(a) Insert a node at the end of the linked list.
(b) Insert a node before specified position.
√ √
(c) Delete a first node of the linked list.
(d) Delete a node after specified position.
5.2 Identify widely used application which use Linked
List for implementation of its important feature.

6. Tree

6.1 Write a program which create binary search tree.


6.2 Implement recursive tree traversing methods in-
order, pre-order and post-order traversal √ √
6.3 Identify widely used application which use Tree data
structure for implementation of its important feature.

7. Graph

7.1 Write a program to perform BFS and DFS on given


graph.
7.2 Identify widely used application which use Graph √ √
data structure for implementation of its important
feature.

8. Searching

8.1 Write a program to implement Linear Search.


√ √
8.2 Write a program to implement Binary Search.
Data Structure (3130702) 230170146053

8.3 Identify widely used application which use


Searching technique for implementation of its
important feature.

9. Sorting

9.1 Write a program to implement Quick Sort


9.2 Write a program to implement Merge Sort
9.3 Write a program to implement Bubble Sort
√ √
9.4 Identify widely used application which use Sorting
technique for implementation of its important
feature.

10 Hashing and File Structure

10.1 Write a program to create hash table and handle


the collision using linear probing.
10.2 Write a program to demonstrate the file primitives
such as fopen, fclose, fprintf. √ √
10.3 Identify widely used application which use
Hashing technique for implementation of its
important feature.
Data Structure (3130702) 230170146053
Industry Relevant Skills

The following industry relevant competencies are expected to be developed in the student by
undertaking the practical work of this laboratory.
1. Will be able to classify data structures and identify storage representation of primitive
and non-primitive data structures
2. Will be able to implement various operations on Stack, Queue, Link list, Tree, Graph,
Hashing and File operations.
3. Will be able to understand need of sorting and searching for various applications
4. Will be able to apply various data structure to design real time applications in efficient
manner.

Guidelines for Faculty members

1. Teacher should provide the guideline with demonstration of practical to the students
with all features.
2. Teacher shall explain basic concepts/theory related to the experiment to the students before
starting of each practical
3. Involve all the students in performance of each experiment.
4. Teacher is expected to share the skills and competencies to be developed in the
students and ensure that the respective skills and competencies are developed in the
students after the completion of the experimentation.
5. Teachers should give opportunity to students for hands-on experience after the
demonstration.
6. Teacher may provide additional knowledge and skills to the students even though not
covered in the manual but are expected from the students by concerned industry.
7. Give practical assignment and assess the performance of students based on task
assigned to check whether it is as per the instructions or not.
8. Teacher is expected to refer complete curriculum of the course and follow the
guidelines for implementation.

Instructions for Students

1. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination scheme,
skill set to be developed etc.
2. Students will have to perform experiments on computer system on which C/C++ compiler
is installed to execute programs of data structure.
3. Students should develop programs and execute all the programs using C/C++ compiler.
Students have to show output of each program in their practical file.
4. Students are instructed to submit practical list as per given sample list shown on next page.
5. Student should develop a habit of submitting the experimentation work as per the schedule
and s/he should be well prepared for the same.
Data Structure (3130702) 230170146053
Common Safety Instructions

Students are expected to

1. Switch on the PC carefully (not to use wet hands).


2. Shutdown the PC properly at the end of your Lab.
3. Carefully handle the peripherals (Mouse, Keyboard, Network cable etc).
4. Use Laptop in lab after getting permission from Teacher.
5. Carefully handle all lab resources.
Data Structure (3130702) 230170146053

Index
(Progressive Assessment Sheet)

Date
Date of Assessme Sign. of
Sr. Page of Remar
No.
Objective(s) of Experiment submiss nt Teacher
No. perfor ks
ion Marks with date
mance

1. Classification of Data Structure and Stack


1.1 Classify various data structures
1.2 Implement a program for stack that
performs following operations using array.
(a) PUSH (b) POP (c) PEEP (d) CHANGE
(e) DISPLAY
1.3 Implement a program to convert infix
notation to postfix notation using stack.
1.4 Write a program to implement Tower of
Hanoi problem.
1.5 Identify widely used application which use
stack data structure for implementation of
its important feature.
2. Queue
2.1 Write a program to implement QUEUE
using arrays that performs following
operations (a) INSERT (b) DELETE (c)
DISPLAY
2.2 Write a program to implement Circular
Queue using arrays that performs following
operations. (a) INSERT (b) DELETE (c)
DISPLAY
2.3 Identify widely used application which use
Queue data structure for implementation of
its important feature.
3. Singly linked list
3.1 Write a menu driven program to implement
following operations on the singly linked
list.
(a) Insert a node at the front of the linked
list.
(b) Insert a node at the end of the linked list.
(c) Insert a node such that linked list is in
ascending order.(according to info.
Field)
(d) Delete a first node of the linked list.
Data Structure (3130702) 230170146053

(e) Delete a node before specified position.


(f) Delete a node after specified position.
3.2 Write a program to implement stack using
linked list.
3.3 Write a program to implement queue using
linked list.
4. Doubly linked list
4.1 Write a program to implement following
operations on the doubly linked list.
(a) Insert a node at the front of the linked
list.
(b) Insert a node at the end of the linked
list.
(c) Delete a last node of the linked list.
(d) Delete a node before specified position.
5. Circular linked list
5.1 Write a program to implement following
operations on the circular linked list.
(a) Insert a node at the end of the linked
list.
(b) Insert a node before specified position.
(c) Delete a first node of the linked list.
(d) Delete a node after specified position.
5.2 Identify widely used application which use
Linked List for implementation of its
important feature.
6. Tree
6.1 Write a program which create binary search
tree.
6.2 Implement recursive tree traversing
methods in-order, pre-order and post-order
traversal.
6.3 Identify widely used application which use
Tree data structure for implementation of its
important feature.
7. Graph
7.1 Write a program to perform BFS and DFS
on given graph.
7.2 Identify widely used application which use
Graph data structure for implementation of
its important feature.
Data Structure (3130702) 230170146053

8. Searching
8.1 Write a program to implement Linear
Search.
8.2 Write a program to implement Binary
Search.
8.3 Identify widely used application which use
Searching technique for implementation of
its important feature.
9. Sorting
9.1 Write a program to implement Quick Sort
9.2 Write a program to implement Merge Sort
9.3 Write a program to implement Bubble Sort
9.4 Identify widely used application which use
Sorting technique for implementation of its
important feature.
10. Hashing and File Structure
10.1Write a program to create hash table and
handle the collision using linear probing.
10.2Write a program to demonstrate the file
primitives such as fopen, fclose, fprintf.
10.3Identify widely used application which use
Hashing technique for implementation of
its important feature.
Total
Data Structure (3130702) 230170146053
Experiment No – 1
AIM: Classification of Data Structure and Stack

1.1 Classify various data structures


1.2 Implement a program for stack that performs following operations using array. (a) PUSH (b)
POP (c) PEEP (d) CHANGE (e) DISPLAY
1.3 Implement a program to convert infix notation to postfix notation using stack.
1.4 Write a program to implement Tower of Hanoi problem.
1.5 Identify widely used application which use stack data structure for implementation of its
important feature.

Date:31/7/24

Competency and Practical Skills: Logic building and programming

Relevant CO: CO1, CO2, CO5

Objectives: (a) To analyze various data structures


(b) To understand the concepts of stack
(c) To implement various applications of the stack

Equipment/Instruments: Computer System with C/C++ compiler

Safety and necessary Precautions:

✓ Operate computer system carefully and responsibly.


✓ Use required lab resources cautiously

Theory:

Data Structure

Data structures are a fundamental concept in computer science that enable efficient storage and
manipulation of data. They are used to organize and store data in a manner that allows for optimal
performance of algorithms. The selection of a suitable data structure begins with the choice of an
abstract data type, which defines the operations that can be performed on the data. Well-designed
data structures can perform a wide range of critical operations while using minimal resources such
as execution time and memory space. In essence, data structure introduction refers to the
arrangement of data in a computer's memory in a way that enables rapid access by the processor for
the required calculations.

Stack

A stack is a data structure that follows the last-in first-out (LIFO) principle, meaning that objects
are inserted and removed from the container in a particular order. In pushdown stacks, only two
Page No
Data Structure (3130702) 230170146053

operations are allowed: pushing an item onto the stack, and popping an item off the top of the stack.
Access to the stack is limited, as elements can only be added and removed from the top. When an
item is pushed onto the stack, it becomes the new top item. Conversely, when an item is popped off
the stack, it is removed from the top.

To illustrate this concept, consider a stack of books. Just as you can only remove the top book, you
can only add a new book to the top of the stack. A stack can also have a limited capacity. If the
stack is already full and there is no space to add a new item, it is said to be in an overflow state. On
the other hand, if the stack is empty and an item is removed, it is in an underflow state, meaning
that no items are present in the stack to be removed.

A stack is an abstract data structure that operates on the LIFO principle, where the last item added
is the first item to be removed. Items can be inserted and deleted at one end called the top, creating
a structure that resembles a closed tube on one side.

✓ The add operation of the stack is called push operation


✓ The delete operation is called as pop operation.
✓ Push operation on a full stack causes stack overflow.
✓ Pop operation on an empty stack causes stack underflow.
✓ SP is a pointer, which is used to access the top element of the stack.
✓ If you push elements that are added at the top of the stack;
✓ In the same way when we pop the elements, the element at the top of the stack is deleted.

There are two operations applied on stack they are

(1) PUSH
(2) POP

In-fix- to Postfix Conversion:

Procedure to convert from infix expression to postfix expression is as follows:

1. Start scanning the infix expression from left to right.


2. If the symbol scanned is a left parenthesis, push it onto the stack.
3. If the scanned symbol is an operand, place it directly into the postfix expression output.
4. If the symbol scanned is a right parenthesis, continue to pop all items from the stack and
place them into the postfix expression output until a matching left parenthesis is found.
5. If the scanned symbol is an operator, remove all operators from the stack and place them in
the postfix expression output if and only if the precedence of the operator on top of the stack
is greater than or equal to the precedence of the scanned operator. Then push the scanned
operator onto the stack; otherwise, push the scanned operator onto the stack.

Page No
Data Structure (3130702) 230170146053

1.1 Classify various data structures

Classification of Data Structures:

Data structures can be classified as

1. Primitive data structure


2. Non-Primitive data structure
(a) Linear data structure
(b) Non-linear data structure

1. Primitive data structures: Primitive data structures are simple data structures
constructed using the standard data types of a computer language. Examples of primitive
data structures include variables, arrays, pointers, structures, unions, and more. These
structures are used to build more complex data structures

2. Non-primitive data structures: Non-primitive data structures are constructed using


primitive data structures and have specific functionality. They can be designed by a user
and are classified into two categories: linear data structures and non-linear data structures.

(a) Linear data structures

Linear data structures are arranged as a continuous set of data elements in the memory
and can be constructed using array data types. In linear data structures, the adjacency
relationship between data elements is maintained.

Operations applied on linear data structure:

The following list of operations applied on linear data structures

✓ Add an element
✓ Delete an element
✓ Traverse
✓ Sort the list of elements
✓ Search for a data element

Examples of linear data structure

✓ Stack
✓ Queue
✓ Tables
✓ List
✓ Linked Lists.

Page No
Data Structure (3130702) 230170146053

(b) Non-linear Data Structure:

Non-linear data structures are not arranged in a continuous manner and include data
structures such as trees and graphs. These structures can be used to represent complex
relationships between data elements.

Operations applied on non-linear data structures:

The following list of operations applied on non-linear data structures.

✓ Add elements
✓ Delete elements
✓ Display the elements
✓ Sort the list of elements
✓ Search for a data element

Examples of non-linear data structure

✓ Tree
✓ Decision tree
✓ Graph
✓ Forest

1.2 Implement a program for stack that performs following operations using array.
(a) PUSH (b) POP (c) PEEP (d) CHANGE (e) DISPLAY

Program:

#include<stdio.h>
#define size 5

struct stack
{
int a[size],top;
int temp[size];
}s;

void push()
{
int value;
printf(" Enter value to be pushed: ");
scanf("%d", &value);
s.top = s.top + 1;
s.a[s.top] = value;
}
Page No
Data Structure (3130702) 230170146053

void pop()
{
printf(" Popped element is %d\n", s.a[s.top]);
s.top = s.top - 1;
}

void peep()
{
printf(" The value at top position is : %d\n", s.a[s.top]);
}

void display()
{
int i;
printf(" The stack contains: ");
for(i=s.top; i>=0; i--)
{
printf("\t%d", s.a[i]);
}
printf("\n");
}

void change(int index, int new_element)


{
int i, j=-1;
for(i=s.top; i>index; i--)
{
s.temp[++j] = s.a[s.top--];
}
s.a[s.top] = new_element;
for(i = j; i>-1; i--)
{
s.a[++s.top] = s.temp[j--];
}
}

void main()
{
s.top = -1;
int choice, index, new_element;
do
{
printf("\n STACK IMPLEMENTATION PROGRAM");

Page No
Data Structure (3130702) 230170146053
printf("\n 1. PUSH 2. POP 3. PEEP 4. CHANGE 5. DISPLAY 0. EXIT\n");
printf("\n Enter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
if(s.top == size-1)
{
printf("\tSTACK OVERFLOW\n");
}
else
{
push();
}
break;
case 2:
if(s.top == -1)
{
printf("\tSTACK UNDERFLOW\n");
}
else
{
pop();
}
break;
case 3:
if(s.top == -1)
{
printf("\tStack is empty.\n");
}
else
{
peep();
}
break;
case 4:
printf(" Enter index no : ");
scanf("%d",&index);

if(index<0 || index>s.top)
{
printf("\tINVALID INDEX NUMBER\n");
}
else
{
printf(" Enter new element: ");

Page No
Data Structure (3130702) 230170146053
scanf("%d", &new_element);
change(index, new_element);
}
break;
case 5:
if(s.top == -1)
{
printf("\t Stack is empty.\n");
}
else
{
display();
}
break;
case 0:
printf("\tEND OF PROGRAM");
break;
default :
printf("\tINVALID CHOICE\n");
}

} while(choice != 0);

Output:

Stack Operations:
1. PUSH 2. POP 3. PEEP 4. CHANGE 5. DISPLAY 6. EXIT
Enter your choice: 1
Enter the value to push: 711
Pushed 711

Stack Operations:
1. PUSH 2. POP 3. PEEP 4. CHANGE 5. DISPLAY 6. EXIT
Enter your choice: 1
Enter the value to push: 53
Pushed 53

Stack Operations:
1. PUSH 2. POP 3. PEEP 4. CHANGE 5. DISPLAY 6. EXIT
Enter your choice: 1
Enter the value to push: 1205
Pushed 1205

Stack Operations:

Page No
Data Structure (3130702) 230170146053
1. PUSH 2. POP 3. PEEP 4. CHANGE 5. DISPLAY 6. EXIT
Enter your choice: 2
Popped 1205

Stack Operations:
1. PUSH 2. POP 3. PEEP 4. CHANGE 5. DISPLAY 6. EXIT
Enter your choice: 3
Top element is: 53

Stack Operations:
1. PUSH 2. POP 3. PEEP 4. CHANGE 5. DISPLAY 6. EXIT
Enter your choice: 4
Enter the position to change: 2
Enter the new value: 1205
Changed element at position 2 to 1205

Stack Operations:
1. PUSH 2. POP 3. PEEP 4. CHANGE 5. DISPLAY 6. EXIT
Enter your choice: 5
Stack elements are: 711 1205

Stack Operations:
1. PUSH 2. POP 3. PEEP 4. CHANGE 5. DISPLAY 6. EXIT
Enter your choice: 6

1.3 Implement a program to convert infix notation to postfix notation using stack.

Program:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
#define MAX 20

char st[MAX];
int top=-1;
void push(char st[], char);
char pop(char st[]);
void InfixtoPostfix(char source[], char target[]);
int getPriority(char);

int main()
{

Page No
Data Structure (3130702) 230170146053
char infix[100], postfix[100];
printf("\n Enter any infix expression : ");
scanf("%s",infix);
strcpy(postfix, "");
InfixtoPostfix(infix, postfix);
printf("\n The corresponding postfix expression is : ");
puts(postfix);
getch();

return 0;
}

void InfixtoPostfix(char source[], char target[])


{
int i=0, j=0;
char temp;
strcpy(target, "");
while(source[i]!='\0')
{
if(source[i]=='(')
{
push(st, source[i]);
i++;
}
else if(source[i] == ')')
{
while((top!=-1) && (st[top]!='('))
{
target[j] = pop(st);
j++;
}
if(top==-1)
{
printf("\n INCORRECT EXPRESSION");exit(1);
}
temp = pop(st);//remove left parenthesis
i++;
}
else if(isdigit(source[i]) || isalpha(source[i]))
{
target[j] = source[i];
j++;
i++;
}
else if (source[i] == '+' || source[i] == '-' || source[i] == '*' || source[i] == '/' || source[i]
== '%')

Page No
Data Structure (3130702) 230170146053
{
while( (top!=-1) && (st[top]!= '(') && (getPriority(st[top]) >= getPriority(source[i])))
{
target[j] = pop(st);
j++;
}
push(st, source[i]);
i++;
}
else
{
printf("\n INCORRECT ELEMENT IN EXPRESSION");exit(1);
}
}
while((top!=-1) && (st[top]!='('))
{
target[j] = pop(st);
j++;
}
target[j]='\0';
}

int getPriority(char op)


{
if(op=='/' || op == '*' || op=='%')
return 1;
else if(op=='+' || op=='-')
return 0;
}
void push(char st[], char val)
{
if(top==MAX-1)
{
printf("\n STACK OVERFLOW");
}
else
{
top++;
st[top]=val;
}
}

char pop(char st[])


{
char val=' ';
if(top==-1)

Page No
Data Structure (3130702) 230170146053
{
printf("\n STACK UNDERFLOW");
}
else
{
val=st[top];
top--;
}

return val;
}

Output:

1.4 Write a program to implement Tower of Hanoi problem.

Program:

#include <stdio.h>

void main()
{
int n;
printf("\n Enter the number of rings: ");
scanf("%d", &n);
move(n,'A', 'C', 'B');
}
void move(int n, char source, char dest, char spare)
{
if (n==1)
printf("\n Move from %c to %c",source,dest);
else
{
move(n-1, source, spare, dest);
move(1, source, dest, spare);
move(n-1, spare, dest, source);
}
}

Page No
Data Structure (3130702) 230170146053

Output:

Enter the number of disks: 3


The sequence of moves involved in the Tower of Hanoi are:
Move disk 1 from rod A to rod C
Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C

1.5 Identify widely used application which use stack data structure for implementation of its
important feature.

Stack Applications:

1. Stack is used by compilers to check for balancing of parentheses, brackets and braces.
2. Stack is used to evaluate a postfix expression.
3. Stack is used to convert an infix expression into postfix/prefix form.
4. In recursion, all intermediate arguments and return values are stored on the processor’s
stack.
5. During a function call the return address and arguments are pushed onto a stack and on
return they are popped off.
6. Depth first search uses a stack data structure to find an element from a graph.

Observations:

● Stack data structure is linear data structure.


● In stack element is stored in Last-in-first-out(LIFO) manner.
● It allow insertion and deletion in only one end.

Conclusion:

Due to LIFO characteristic stack is used in


● Recursion for keeping track of function call
● Reversing character
● Solving combinatorial problems using backtracking

Quiz:

(1) List various stack operations


(2) Differentiate FIFO and LIFO
(3) Explain infix, prefix and postfix expressions
Page No
Data Structure (3130702) 230170146053

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

1. Paul G. Sorenson Publisher-Tata McGraw Hill.

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

Page No
Data Structure (3130702) 230170146053

Experiment No: 2

AIM : Queue

2.1 Write a program to implement QUEUE using arrays that performs following
operations (a)INSERT (b) DELETE (c) DISPLAY
2.2 Write a program to implement Circular Queue using arrays that performs following
operations. (a) INSERT (b) DELETE (c) DISPLAY
2.3 Identify widely used application which uses Queue data structure for implementation
of its important feature.

Date: 7/8/24
Competency and Practical Skills: Logic building and programming

Relevant CO: CO2, CO5

Objectives: (a) To understand the concepts of Queue


(b) To analyze different algorithms on Queue
(c) To implement various operations on Queue

Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

✓ Operate computer system carefully and responsibly.


✓ Use required lab resources cautiously

Theory:

Queue

A queue is a data structure that follows the First In, First Out (FIFO) principle. It is a special type
of list where items are inserted at the rear and deleted from the front end. Queues can be compared
to real-world scenarios, such as people waiting in line at a bank.

There are various types of Queue in data structure

✓ Queue
✓ Circular Queue
✓ D-Queue
✓ Priority Queue

Page No
Data Structure (3130702) 230170146053

2.1 Write a program to implement QUEUE using arrays that performs following
operations. (a)INSERT (b) DELETE (c) DISPLAY

Program:

#include <stdio.h>
#include <stdlib.h>

#define MAX 5

struct Queue {
int items[MAX];
int front;
int rear;
};

struct Queue* createQueue() {


struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = -1;
q->rear = -1;
return q;
}

int isFull(struct Queue* q) {


return q->rear == MAX - 1;
}

int isEmpty(struct Queue* q) {


return q->front == -1 || q->front > q->rear;
}

void insert(struct Queue* q, int value) {


if (isFull(q)) {
printf("Queue is full! Cannot insert %d\n", value);
} else {
if (q->front == -1) {
q->front = 0;
}
q->rear++;
q->items[q->rear] = value;
printf("Inserted %d\n", value);
}
}

Page No
Data Structure (3130702) 230170146053

void delete(struct Queue* q) {


if (isEmpty(q)) {
printf("Queue is empty! Cannot delete\n");
} else {
printf("Deleted %d\n", q->items[q->front]);
q->front++;
if (q->front > q->rear) {
q->front = -1;
q->rear = -1;
}
}
}

void display(struct Queue* q) {


if (isEmpty(q)) {
printf("Queue is empty!\n");
} else {
printf("Queue elements are: ");
for (int i = q->front; i <= q->rear; i++) {
printf("%d ", q->items[i]);
}
printf("\n");
}
}

int main() {
struct Queue* q = createQueue();
int choice, value;

while (1) {
printf("\nQueue Operations: \n");
printf("1. INSERT\n2. DELETE\n3. DISPLAY\n4. EXIT\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &value);
insert(q, value);
break;
case 2:
delete(q);
break;
case 3:

Page No
Data Structure (3130702) 230170146053
display(q);
break;
case 4:
exit(0);
default:
printf("Invalid choice! Please enter a valid option.\n");
}
}

return 0;
}

Output:

Page No
Data Structure (3130702) 230170146053

2.2 Write a program to implement Circular Queue using arrays that performs following
operations. (a) INSERT (b) DELETE (c) DISPLAY

Program:

#include <stdio.h>
#include <stdlib.h>

#define MAX 5

struct CircularQueue
{
int items[MAX];
int front;
int rear;
};

struct CircularQueue *createQueue()


{
struct CircularQueue *cq = (struct CircularQueue *)malloc(sizeof(struct CircularQueue));
cq->front = -1;
cq->rear = -1;
return cq;
}

int isFull(struct CircularQueue *cq)


{
return ((cq->rear + 1) % MAX == cq->front);
}

int isEmpty(struct CircularQueue *cq)


{
return (cq->front == -1);
}
Page No
Data Structure (3130702) 230170146053

void insert(struct CircularQueue *cq, int value)


{
if (isFull(cq))
{
printf("Circular Queue is full! Cannot insert %d\n", value);
}
else
{
if (isEmpty(cq))
{
cq->front = 0;
}
cq->rear = (cq->rear + 1) % MAX;
cq->items[cq->rear] = value;
printf("Inserted %d\n", value);
}
}

void delete(struct CircularQueue *cq)


{
if (isEmpty(cq))
{
printf("Circular Queue is empty! Cannot delete\n");
}
else
{
printf("Deleted %d\n", cq->items[cq->front]);
if (cq->front == cq->rear)
{

cq->front = -1;
cq->rear = -1;
}
else
{
cq->front = (cq->front + 1) % MAX;
}
}
}

void display(struct CircularQueue *cq)


{
if (isEmpty(cq))
{
printf("Circular Queue is empty!\n");

Page No
Data Structure (3130702) 230170146053
}
else
{
int i = cq->front;
printf("Circular Queue elements are: ");
while (1)
{
printf("%d ", cq->items[i]);
if (i == cq->rear)
break;
i = (i + 1) % MAX;
}
printf("\n");
}
}

int main()
{
struct CircularQueue *cq = createQueue();
int choice, value;

while (1)
{
printf("\nCircular Queue Operations: \n");
printf("1. INSERT\n2. DELETE\n3. DISPLAY\n4. EXIT\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
{
case 1:
printf("Enter the value to insert: ");
scanf("%d", &value);
insert(cq, value);
break;
case 2:
delete (cq);
break;
case 3:
display(cq);
break;
case 4:
exit(0);
default:
printf("Invalid choice! Please enter a valid option.\n");
}

Page No
Data Structure (3130702) 230170146053
}

return 0;
}

Output:

Page No
Data Structure (3130702) 230170146053

2.3 Identify widely used application which uses Queue data structure for implementation
of its important feature.

Applications that use Queue data structures:

1. Email Services: Many email services use Queues for managing the delivery of emails, ensuring they
are sent and received in the correct order.

2. Print Job Queues: Printers and print servers use Queues to manage print jobs in a first come, first-
served manner.

3. Web Servers: Web servers often use Queues to handle incoming HTTP requests from clients,
ensuring fair and efficient processing.

4. Operating Systems: Operating systems use Queues for scheduling tasks and managing various
system processes.

5. Customer Support Systems: Customer support applications use Queues to manage incoming
support tickets, assigning them to available agents or support teams.

6. Ride-Sharing Apps: Ride-sharing apps like Uber and Lyft use Queues to match drivers with riders
based on location and availability.

7. Online Retailers: E-commerce websites use Queues to manage order processing, ensuring that
orders are fulfilled in the order they are received.

8. Banking Systems: Banks use Queues for managing customer transactions, such as withdrawals and
deposits, in an organized and secure manner.

9. Traffic Management Systems: Traffic management systems use Queues to control the f low of
vehicles at intersections, toll booths, and parking lots.

10. Social Media Platforms: Social media platforms like Twitter may use Queues to handle real- time
updates and notifications to users.
Page No
Data Structure (3130702) 230170146053

These applications and systems use Queue data structures to efficiently manage tasks, requests, and
events in various domains.

Observations:

We can perform Enqueue, Dequeue or Delete using QUEUE.

Conclusion:

QUEUE follows FIFO to arrange its objects.

Quiz:

(1) Explain concepts of Queue


(2) Define DQueue
(3) Differentiate Circular Queue and Priority Queue

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International

3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.


4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

Paul G. Sorenson Publisher-Tata McGraw Hill.

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

Page No
Data Structure (3130702) 230170146053

Experiment No: 3

AIM : Singly linked list

3.1 Write a menu driven program to implement following operations on the singly linked
list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Insert a node such that linked list is in ascending order. (According to INFO field)
(d) Delete a first node of the linked list.
(e) Delete a node before specified position.
(f) Delete a node after specified position.
3.2 Write a program to implement stack using linked list
3.3 Write a program to implement queue using linked list.

Date: 14/8/24

Competency and Practical Skills: Logic building and programming

Relevant CO: CO2, CO5

Objectives: (a) To understand the concepts of singly linked list


(b) To analyze different algorithms on singly link list
(c) To implement various operations on singly link list

Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

✓ Operate computer system carefully and responsibly.


✓ Use required lab resources cautiously

Theory:

Singly link list

A linked list is a type of data structure that stores a collection of non-sequential data items. Unlike
arrays, linked lists are dynamic and their size can be changed during program execution. Each data
item in a linked list has a pointer that holds the memory address of the next data item in the list. The
data items in a linked list may not be stored in consecutive memory locations, but their pointers
make it easy to access them in any order.

A singly linked list, also known as a linear linked list, is a type of linked list in which all nodes are
connected together sequentially. Each node in a singly linked list contains data and a pointer to the

Page No
Data Structure (3130702) 230170146053
next node. The last node's pointer is set to null. The limitation of a singly linked list is that it can
only be traversed in one direction, in a forward direction.

Operations on singly linked list

✓ Insert
- Insert at first position
- Insert at last position
- Insert into ordered list
✓ Delete
✓ Traverse list (Print list)
✓ Copy linked list

3.1 Write a menu driven program to implement following operations on the singly linked
list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Insert a node such that linked list is in ascending order.(According to INFO field)
(d) Delete a first node of the linked list.
(e) Delete a node before specified position.
(f) Delete a node after specified position.

Program:
#include <stdio.h>
#include <stdlib.h>

// Define structure for a node in the linked list


struct Node {
int data;
struct Node* next;
};

// Head pointer to the list


struct Node* head = NULL;

// Function to insert a node at the front


void insertAtFront(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = head;
head = newNode;
printf("%d inserted at the front.\n", value);
}

// Function to insert a node at the end

Page No
Data Structure (3130702) 230170146053
void insertAtEnd(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;

if (head == NULL) {
head = newNode;
} else {
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
printf("%d inserted at the end.\n", value);
}

// Function to insert a node in ascending order based on the data field


void insertInAscendingOrder(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;

if (head == NULL || head->data >= value) {


newNode->next = head;
head = newNode;
} else {
struct Node* temp = head;
while (temp->next != NULL && temp->next->data < value) {
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
printf("%d inserted in ascending order.\n", value);
}

// Function to delete the first node of the linked list


void deleteFirstNode() {
if (head == NULL) {
printf("List is empty.\n");
return;
}
struct Node* temp = head;
head = head->next;

Page No
Data Structure (3130702) 230170146053
printf("%d deleted from the front.\n", temp->data);
free(temp);
}

// Function to delete the node before a specified position


void deleteBeforePosition(int position) {
if (head == NULL || position <= 1) {
printf("No node exists before the specified position.\n");
return;
}

struct Node* temp = head;


struct Node* prev = NULL;

for (int i = 1; i < position - 1 && temp != NULL; i++) {


prev = temp;
temp = temp->next;
}

if (temp == NULL || temp->next == NULL) {


printf("No node exists before the specified position.\n");
} else {
if (prev == NULL) {
head = temp->next;
} else {
prev->next = temp->next;
}
printf("%d deleted before position %d.\n", temp->data, position);
free(temp);
}
}

// Function to delete the node after a specified position


void deleteAfterPosition(int position) {
struct Node* temp = head;

for (int i = 1; i < position && temp != NULL; i++) {


temp = temp->next;
}

if (temp == NULL || temp->next == NULL) {


printf("No node exists after the specified position.\n");
} else {
struct Node* delNode = temp->next;
temp->next = delNode->next;

Page No
Data Structure (3130702) 230170146053
printf("%d deleted after position %d.\n", delNode->data, position);
free(delNode);
}
}

// Function to display the linked list


void display() {
if (head == NULL) {
printf("List is empty.\n");
return;
}

struct Node* temp = head;


printf("Linked list: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// Main function to drive the menu


int main() {
int choice, value, position;

while (1) {
printf("\nLinked List Operations:\n");
printf("1. Insert at front\n");
printf("2. Insert at end\n");
printf("3. Insert in ascending order\n");
printf("4. Delete first node\n");
printf("5. Delete node before specified position\n");
printf("6. Delete node after specified position\n");
printf("7. Display linked list\n");
printf("8. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to insert at front: ");
scanf("%d", &value);
insertAtFront(value);
break;
case 2:
printf("Enter value to insert at end: ");

Page No
Data Structure (3130702) 230170146053
scanf("%d", &value);
insertAtEnd(value);
break;
case 3:
printf("Enter value to insert in ascending order: ");
scanf("%d", &value);
insertInAscendingOrder(value);
break;
case 4:
deleteFirstNode();
break;
case 5:
printf("Enter position before which to delete: ");
scanf("%d", &position);
deleteBeforePosition(position);
break;
case 6:
printf("Enter position after which to delete: ");
scanf("%d", &position);
deleteAfterPosition(position);
break;
case 7:
display();
break;
case 8:
exit(0);
default:
printf("Invalid choice, please try again.\n");
}
}

return 0;
}

Output:

Linked List Operations:


1. Insert at front
2. Insert at end
3. Insert in ascending order
4. Delete first node
5. Delete node before specified position
6. Delete node after specified position
7. Display linked list
8. Exit

Page No
Data Structure (3130702) 230170146053

Enter your choice: 1


Enter value to insert at front: 10
10 inserted at the front.

Linked List Operations:


1. Insert at front
2. Insert at end
3. Insert in ascending order
4. Delete first node
5. Delete node before specified position
6. Delete node after specified position
7. Display linked list
8. Exit
Enter your choice: 2
Enter value to insert at end: 20
20 inserted at the end.

Linked List Operations:


1. Insert at front
2. Insert at end
3. Insert in ascending order
4. Delete first node
5. Delete node before specified position
6. Delete node after specified position
7. Display linked list
8. Exit
Enter your choice: 3
Enter value to insert in ascending order: 15
15 inserted in ascending order.

Linked List Operations:


1. Insert at front
2. Insert at end
3. Insert in ascending order
4. Delete first node
5. Delete node before specified position
6. Delete node after specified position
7. Display linked list
8. Exit
Enter your choice: 7
Linked list: 10 -> 15 -> 20 -> NULL

Linked List Operations:


1. Insert at front
2. Insert at end

Page No
Data Structure (3130702) 230170146053

3. Insert in ascending order


4. Delete first node
5. Delete node before specified position
6. Delete node after specified position

7. Display linked list


8. Exit
Enter your choice: 4
10 deleted from the front.

Linked List Operations:


1. Insert at front
2. Insert at end
3. Insert in ascending order
4. Delete first node
5. Delete node before specified position
6. Delete node after specified position
7. Display linked list
8. Exit
Enter your choice: 7
Linked list: 15 -> 20 -> NULL

Linked List Operations:


1. Insert at front
2. Insert at end
3. Insert in ascending order
4. Delete first node
5. Delete node before specified position
6. Delete node after specified position
7. Display linked list
8. Exit
Enter your choice: 5
Enter position before which to delete: 2
No node exists before the specified position.

Linked List Operations:


1. Insert at front
2. Insert at end
3. Insert in ascending order
4. Delete first node
5. Delete node before specified position
6. Delete node after specified position
7. Display linked list
8. Exit
Enter your choice: 6

Page No
Data Structure (3130702) 230170146053

Enter position after which to delete: 1


20 deleted after position 1.

Linked List Operations:


1. Insert at front

2. Insert at end
3. Insert in ascending order
4. Delete first node
5. Delete node before specified position
6. Delete node after specified position
7. Display linked list
8. Exit
Enter your choice: 7
Linked list: 15 -> NULL

Linked List Operations:


1. Insert at front
2. Insert at end
3. Insert in ascending order
4. Delete first node
5. Delete node before specified position
6. Delete node after specified position
7. Display linked list
8. Exit
Enter your choice: 8

3.2 Write a program to implement stack using linked list

Program:

#include <stdio.h>
#include <stdlib.h>

// Define structure for a stack node


struct Node {
int data;
struct Node* next;
};

// Define the top of the stack (initially NULL)


struct Node* top = NULL;

// Function to push an element onto the stack


void push(int value) {

Page No
Data Structure (3130702) 230170146053

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));


if (newNode == NULL) {
printf("Stack overflow\n");
return;
}

newNode->data = value;
newNode->next = top;
top = newNode;
printf("%d pushed onto the stack.\n", value);
}

// Function to pop an element from the stack


void pop() {
if (top == NULL) {
printf("Stack underflow\n");
return;
}

struct Node* temp = top;


printf("%d popped from the stack.\n", top->data);
top = top->next;
free(temp);
}

// Function to display the elements of the stack


void display() {
if (top == NULL) {
printf("Stack is empty.\n");
return;
}

struct Node* temp = top;


printf("Stack elements: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// Main function to implement the menu-driven interface


int main() {
int choice, value;

Page No
Data Structure (3130702) 230170146053

while (1) {
printf("\nStack Operations using Linked List:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");

printf("Enter your choice: ");


scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(value);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}

Output:

Stack Operations using Linked List:


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 711
711 pushed onto the stack.

Stack Operations using Linked List:


1. Push

Page No
Data Structure (3130702) 230170146053

2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 53
53 pushed onto the stack.

Stack Operations using Linked List:


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 1205
1205 pushed onto the stack.

Stack Operations using Linked List:


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
1205 popped from the stack.

Stack Operations using Linked List:


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
53 popped from the stack.

Stack Operations using Linked List:


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
Stack elements: 711 -> NULL

Stack Operations using Linked List:


1. Push
2. Pop
3. Display

Page No
Data Structure (3130702) 230170146053

4. Exit
Enter your choice: 4

=== Code Execution Successful ===

3.3 Write a program to implement queue using linked list.

Program:

#include <stdio.h>
#include <stdlib.h>

// Define structure for a queue node


struct Node {
int data;
struct Node* next;
};

// Define the front and rear of the queue


struct Node* front = NULL;
struct Node* rear = NULL;

// Function to enqueue an element to the queue


void enqueue(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Queue overflow\n");
return;
}
newNode->data = value;
newNode->next = NULL;

if (rear == NULL) {
// If the queue is empty, both front and rear point to the new node
front = rear = newNode;
} else {
// Insert the new node at the end and update rear
rear->next = newNode;
rear = newNode;
}
printf("%d enqueued to the queue.\n", value);
}

Page No
Data Structure (3130702) 230170146053
// Function to dequeue an element from the queue
void dequeue() {
if (front == NULL) {
printf("Queue underflow\n");
return;
}

struct Node* temp = front;


printf("%d dequeued from the queue.\n", front->data);
front = front->next;

if (front == NULL) {
rear = NULL; // If the queue becomes empty, set rear to NULL as well
}

free(temp);
}

// Function to display the queue


void display() {
if (front == NULL) {
printf("Queue is empty.\n");
return;
}

struct Node* temp = front;


printf("Queue elements: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// Main function to implement the menu-driven interface


int main() {
int choice, value;

while (1) {
printf("\nQueue Operations using Linked List:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");

printf("4. Exit\n");

Page No
Data Structure (3130702) 230170146053
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to enqueue: ");
scanf("%d", &value);
enqueue(value);

break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}

Output:

Queue Operations using Linked List:


1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter value to enqueue: 711
711 enqueued to the queue.

Queue Operations using Linked List:


1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter value to enqueue: 53

53 enqueued to the queue.

Page No
Data Structure (3130702) 230170146053

Queue Operations using Linked List:


1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter value to enqueue: 1205
1205 enqueued to the queue.

Queue Operations using Linked List:


1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 2
711 dequeued from the queue.

Queue Operations using Linked List:


1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 2
53 dequeued from the queue.

Queue Operations using Linked List:


1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 2
1205 dequeued from the queue.

Queue Operations using Linked List:


1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 3
Queue is empty.

Queue Operations using Linked List:


1. Enqueue

2. Dequeue

Page No
Data Structure (3130702) 230170146053
3. Display
4. Exit
Enter your choice: 4

Observations:

A linked list is a collection of “nodes” connected together via links. These nodes consist of the
data to be stored and a pointer to the address of the next node within the linked list.

Conclusion:

Linked list can be used to implement stacks, queues, and other abstract data types.In the case
of arrays, the size is limited to the definition, but in linked lists, there is no defined size.

Quiz:
(1) Which are the operations on singly link list?
(2) State the limitation of singly link list
(3) Compare array and singly link list

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

1. Paul G. Sorenson Publisher-Tata McGraw Hill.

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

Page No
Data Structure (3130702) 230170146053

Experiment No: 4

AIM : Doubly linked list

4.1 Write a program to implement following operations on the doubly linked list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Delete a last node of the linked list.
(d) Delete a node before specified position.

Date: 21/8/24

Competency and Practical Skills: Logic building and programming

Relevant CO: CO2, CO5

Objectives: (a) To understand the concepts of doubly linked list


(b) To analyze different algorithms on doubly link list
(c) To implement various operations on doubly link list

Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

✓ Operate computer system carefully and responsibly.


✓ Use required lab resources cautiously

Theory:

Doubly linked list

A doubly linked list is a data structure where each node contains data and two pointers - one to point
to the previous node (LPTR) and another to point to the next node (RPTR). The main advantage of
a doubly linked list is that we can traverse it in any direction, either forward or backward. Another
advantage is that we can delete a node with ease since we have pointers to both the previous and
next nodes. In contrast, a node on a singly linked list cannot be removed unless we have a pointer
to its predecessor. However, the drawback of a doubly linked list is that it requires more memory
than a singly linked list since we need an extra pointer to point to the previous node. In the image,
L and R denote the leftmost and rightmost nodes in the list, respectively. The left link of the L node
and the right link of the R node are both NULL, indicating the end of the list for each direction.

Operations on doubly linked list

✓ Insert
- Insert at first position
Page No
Data Structure (3130702) 230170146053
- Insert at last position
- Insert into ordered list
✓ Delete
✓ Traverse list (Print list)
✓ Copy linked list

4.1 Write a program to implement following operations on the doubly linked list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Delete a last node of the linked list.
(d) Delete a node before specified position.

(a) Insert a node at the front of the linked list.

Program:

#include <stdio.h>
#include <stdlib.h>

// Define structure for a doubly linked list node


struct Node {
int data;
struct Node* prev;
struct Node* next;
};

// Define head of the list (initially NULL)


struct Node* head = NULL;

// Function to insert a node at the front of the doubly linked list


void insertAtFront(int value) {
// Create a new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->prev = NULL;
newNode->next = head;

// If the list is not empty, set the previous head's previous pointer to the new node
if (head != NULL) {
head->prev = newNode;
}

// Set the head to the new node


head = newNode;

printf("%d inserted at the front of the list.\n", value);

Page No
Data Structure (3130702) 230170146053
}

// Function to display the doubly linked list


void display() {
if (head == NULL) {
printf("List is empty.\n");
return;
}

struct Node* temp = head;


printf("Doubly Linked List: ");
while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Main function to implement the menu-driven interface
int main() {
int choice, value;

while (1) {
printf("\nDoubly Linked List Operations:\n");
printf("1. Insert at front\n");
printf("2. Display list\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to insert at front: ");
scanf("%d", &value);
insertAtFront(value);
break;
case 2:
display();
break;
case 3:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;

Page No
Data Structure (3130702) 230170146053
}

Output:

Doubly Linked List Operations:


1. Insert at front
2. Display list
3. Exit
Enter your choice: 1
Enter value to insert at front: 711
711 inserted at the front of the list.

Doubly Linked List Operations:


1. Insert at front
2. Display list
3. Exit
Enter your choice: 1
Enter value to insert at front: 53
53 inserted at the front of the list.

Doubly Linked List Operations:


1. Insert at front
2. Display list
3. Exit
Enter your choice: 2
Doubly Linked List: 53 <-> 711 <-> NULL

Doubly Linked List Operations:


1. Insert at front
2. Display list
3. Exit
Enter your choice: 3

=== Code Execution Successful ===

(b) Insert a node at the end of the linked list.

Program:

#include <stdio.h>
#include <stdlib.h>

// Define structure for a doubly linked list node

Page No
Data Structure (3130702) 230170146053
struct Node {
int data;
struct Node* prev;

struct Node* next;


};

// Define head of the list (initially NULL)


struct Node* head = NULL;

// Function to insert a node at the end of the doubly linked list


void insertAtEnd(int value) {
// Create a new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;

// If the list is empty, set the new node as the head


if (head == NULL) {
newNode->prev = NULL;
head = newNode;
} else {
// Traverse to the last node
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
// Link the new node at the end of the list
temp->next = newNode;
newNode->prev = temp;
}

printf("%d inserted at the end of the list.\n", value);


}
// Function to display the doubly linked list
void display() {
if (head == NULL) {
printf("List is empty.\n");
return;
}

struct Node* temp = head;


printf("Doubly Linked List: ");
while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->next;

Page No
Data Structure (3130702) 230170146053
}
printf("NULL\n");
}

// Main function to implement the menu-driven interface


int main() {
int choice, value;

while (1) {
printf("\nDoubly Linked List Operations:\n");
printf("1. Insert at end\n");
printf("2. Display list\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to insert at end: ");
scanf("%d", &value);
insertAtEnd(value);
break;
case 2:
display();
break;
case 3:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}

Output:

Doubly Linked List Operations:


1. Insert at end
2. Display list
3. Exit
Enter your choice: 1
Enter value to insert at end: 53
53 inserted at the end of the list.

Page No
Data Structure (3130702) 230170146053

Doubly Linked List Operations:


1. Insert at end
2. Display list

3. Exit
Enter your choice: 1
Enter value to insert at end: 711
711 inserted at the end of the list.

Doubly Linked List Operations:


1. Insert at end
2. Display list
3. Exit
Enter your choice: 1
Enter value to insert at end: 1205
1205 inserted at the end of the list.

Doubly Linked List Operations:


1. Insert at end
2. Display list
3. Exit
Enter your choice: 2
Doubly Linked List: 53 <-> 711 <-> 1205 <-> NULL

Doubly Linked List Operations:


1. Insert at end
2. Display list
3. Exit
Enter your choice: 3

=== Code Execution Successful ===

(c) Delete a last node of the linked list.

Program:

#include <stdio.h>
#include <stdlib.h>

// Define structure for a doubly linked list node


struct Node {
int data;
struct Node* prev;

Page No
Data Structure (3130702) 230170146053
struct Node* next;
};

// Define head of the list (initially NULL)


struct Node* head = NULL;

// Function to delete the last node of the doubly linked list


void deleteLastNode() {
// Check if the list is empty
if (head == NULL) {
printf("List is empty.\n");
return;
}

// If there is only one node in the list


if (head->next == NULL) {
free(head);
head = NULL;
printf("Last node deleted.\n");
return;
}

// Traverse to the last node


struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}

// Update the second last node's next pointer


temp->prev->next = NULL;

// Free the last node


free(temp);

printf("Last node deleted.\n");


}

// Function to display the doubly linked list


void display() {
if (head == NULL) {
printf("List is empty.\n");
return;
}
struct Node* temp = head;
printf("Doubly Linked List: ");
while (temp != NULL) {

Page No
Data Structure (3130702) 230170146053
printf("%d <-> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// Function to insert a node at the end of the doubly linked list (for testing purposes)
void insertAtEnd(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;

if (head == NULL) {
newNode->prev = NULL;
head = newNode;
} else {
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}

printf("%d inserted at the end of the list.\n", value);


}

// Main function to implement the menu-driven interface


int main() {
int choice, value;

while (1) {
printf("\nDoubly Linked List Operations:\n");
printf("1. Insert at end\n");
printf("2. Delete last node\n");
printf("3. Display list\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to insert at end: ");
scanf("%d", &value);
insertAtEnd(value);

Page No
Data Structure (3130702) 230170146053
break;
case 2:
deleteLastNode();
break;
case 3:

display();
break;
case 4:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}

Output:

Doubly Linked List Operations:


1. Insert at end
2. Delete last node
3. Display list
4. Exit
Enter your choice: 1
Enter value to insert at end: 711
711 inserted at the end of the list.

Doubly Linked List Operations:


1. Insert at end
2. Delete last node
3. Display list
4. Exit
Enter your choice: 1
Enter value to insert at end: 53
53 inserted at the end of the list.

Doubly Linked List Operations:


1. Insert at end
2. Delete last node
3. Display list
4. Exit
Enter your choice: 3
Doubly Linked List: 711 <-> 53 <-> NULL

Page No
Data Structure (3130702) 230170146053
Doubly Linked List Operations:
1. Insert at end
2. Delete last node
3. Display list

4. Exit
Enter your choice: 2
Last node deleted.

Doubly Linked List Operations:


1. Insert at end
2. Delete last node
3. Display list
4. Exit
Enter your choice: 3
Doubly Linked List: 711 <-> NULL

Doubly Linked List Operations:


1. Insert at end
2. Delete last node
3. Display list
4. Exit
Enter your choice: 4

=== Code Execution Successful ===

(d) Delete a node before specified position.

Program:

#include <stdio.h>
#include <stdlib.h>

// Define structure for a doubly linked list node


struct Node {
int data;
struct Node* prev;
struct Node* next;
};

// Define head of the list (initially NULL)


struct Node* head = NULL;

Page No
Data Structure (3130702) 230170146053
// Function to insert a node at the end of the doubly linked list (for testing)
void insertAtEnd(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;

if (head == NULL) {
newNode->prev = NULL;
head = newNode;
} else {
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}

printf("%d inserted at the end of the list.\n", value);


}

// Function to delete a node before the specified position in the doubly linked list
void deleteBeforePosition(int position) {
if (head == NULL || position <= 1) {
printf("Invalid position or list is empty.\n");
return;
}

struct Node* temp = head;

// Traverse to the node at the specified position


for (int i = 1; i < position && temp != NULL; i++) {
temp = temp->next;
}

// If the specified position is invalid


if (temp == NULL || temp->prev == NULL || temp->prev->prev == NULL) {
printf("No node exists before position %d.\n", position);
return;
}

// Node to be deleted is the previous node of the previous node of temp


struct Node* nodeToDelete = temp->prev;

// Adjust the pointers


if (nodeToDelete->prev != NULL) {

Page No
Data Structure (3130702) 230170146053
nodeToDelete->prev->next = temp;
} else {
head = temp; // Handle the case where the node before the position is the head
}
temp->prev = nodeToDelete->prev;

// Free the memory of the node


free(nodeToDelete);

printf("Node before position %d deleted.\n", position);


}

// Function to display the doubly linked list


void display() {
if (head == NULL) {
printf("List is empty.\n");
return;
}

struct Node* temp = head;


printf("Doubly Linked List: ");
while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// Main function to implement the menu-driven interface


int main() {
int choice, value, position;

while (1) {
printf("\nDoubly Linked List Operations:\n");
printf("1. Insert at end\n");
printf("2. Delete node before specified position\n");
printf("3. Display list\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to insert at end: ");
scanf("%d", &value);
insertAtEnd(value);

Page No
Data Structure (3130702) 230170146053
break;
case 2:
printf("Enter position: ");
scanf("%d", &position);
deleteBeforePosition(position);

break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}

Output:

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position
3. Display list
4. Exit
Enter your choice: 1
Enter value to insert at end: 711
711 inserted at the end of the list.

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position
3. Display list
4. Exit
Enter your choice: 1
Enter value to insert at end: 53
53 inserted at the end of the list.

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position
3. Display list
4. Exit

Page No
Data Structure (3130702) 230170146053
Enter your choice: 1
Enter value to insert at end: 1205
1205 inserted at the end of the list.

Doubly Linked List Operations:


1. Insert at end

2. Delete node before specified position


3. Display list
4. Exit
Enter your choice: 3
Doubly Linked List: 711 <-> 53 <-> 1205 <-> NULL

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position
3. Display list
4. Exit
Enter your choice: 2
Enter position: 3
Node before position 3 deleted.

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position
3. Display list
4. Exit
Enter your choice: 3
Doubly Linked List: 711 <-> 1205 <-> NULL

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position
3. Display list
4. Exit
Enter your choice: 4

=== Code Execution Successful ===

Observations:

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position

Page No
Data Structure (3130702) 230170146053
3. Display list
4. Exit
Enter your choice: 1
Enter value to insert at end: 711
711 inserted at the end of the list.

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position
3. Display list
4. Exit
Enter your choice: 1
Enter value to insert at end: 53
53 inserted at the end of the list.

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position
3. Display list
4. Exit
Enter your choice: 1
Enter value to insert at end: 1205
1205 inserted at the end of the list.

Doubly Linked List Operations:


1. Insert at end

2. Delete node before specified position


3. Display list
4. Exit
Enter your choice: 3
Doubly Linked List: 711 <-> 53 <-> 1205 <-> NULL

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position
3. Display list
4. Exit
Enter your choice: 2
Enter position: 3
Node before position 3 deleted.

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position
3. Display list

Page No
Data Structure (3130702) 230170146053
4. Exit
Enter your choice: 3
Doubly Linked List: 711 <-> 1205 <-> NULL

Doubly Linked List Operations:


1. Insert at end
2. Delete node before specified position
3. Display list
4. Exit
Enter your choice: 4

=== Code Execution Successful ===

Conclusion:

Doubly linked lists provide efficiency in insertion, deletion, and many other operations due to
the presence of previous and next pointers.
Quiz:
(1) Explain structure of a node of doubly link list
(2) Which is the main advantage of doubly link list?
(3) What is the drawback of doubly link list?

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni, Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

1. Paul G. Sorenson Publisher-Tata McGraw Hill.

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

Page No
Data Structure (3130702) 230170146053

Experiment No: 5

AIM : Circular linked list

5.1 Write a program to implement following operations on the circular linked list.
(a) Insert a node at the end of the linked list.
(b) Insert a node before specified position.
(c) Delete a first node of the linked list.
(d) Delete a node after specified position.
5.2 Identify widely used application which uses linked list for implementation of its
important feature.

Date: / / 2024

Competency and Practical Skills: Logic building and programming

Relevant CO: CO2, CO5

Objectives: (a) To understand the concepts of circular linked list


(b) To analyze different algorithms on circular link list
(c) To implement various operations on circular link list

Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

✓ Operate computer system carefully and responsibly.


✓ Use required lab resources cautiously

Theory:

Circular linked list

A circular linked list is similar to a singly linked list, except that the last node points to the first
node, creating a circular arrangement of nodes. Unlike a singly linked list, it does not contain null
pointers. Traversal can only be done in one direction, i.e., the forward direction. The biggest
advantage of a circular linked list is that it saves time when we want to go from the last node to the
first node because it directly points to the first node. A good example of an application where a
circular linked list can be used is a time-sharing problem that can be solved by the operating system.

Operations on circular linked list

✓ Insert
- Insert at first position
- Insert at last position
Page No
Data Structure (3130702) 230170146053
- Insert into ordered list
✓ Delete
✓ Traverse list (Print list)
5.1 Write a program to implement following operations on the circular linked list.
(a) Insert a node at the end of the linked list.
(b) Insert a node before specified position.
(c) Delete a first node of the linked list.
(d) Delete a node after specified position.

(a) Insert a node at the end of the linked list.

Program:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

void insert_at_end(struct Node** head_ref, int data) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* temp = *head_ref;

new_node->data = data;
new_node->next = *head_ref; // Set new node's next to the head (circular nature)

if (*head_ref == NULL) {
*head_ref = new_node;
new_node->next = new_node; // Circular reference
} else {
while (temp->next != *head_ref) {
temp = temp->next;
}

temp->next = new_node;
new_node->next = *head_ref;
}
}

void display(struct Node* head) {


struct Node* temp = head;

if (head == NULL) {
printf("List is empty\n");

Page No
Data Structure (3130702) 230170146053
return;
}

do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);
printf("(head)\n");
}

int main() {
struct Node* head = NULL;

insert_at_end(&head, 10);
insert_at_end(&head, 20);
insert_at_end(&head, 30);
insert_at_end(&head, 40);

printf("Circular Linked List: \n");


display(head);

return 0;
}

Output:

Circular Linked List:


10 -> 20 -> 30 -> 40 -> (head)

(b) Insert a node before specified position.

Program:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;

Page No
Data Structure (3130702) 230170146053
}

void insertAtEnd(struct Node** head, int data) {


struct Node* newNode = createNode(data);

if (*head == NULL) {
*head = newNode;
newNode->next = *head;
} else {
struct Node* temp = *head;

while (temp->next != *head) {


temp = temp->next;
}

temp->next = newNode;
newNode->next = *head;
}
}

void insertBeforePosition(struct Node** head, int data, int position) {


struct Node* newNode = createNode(data);

if (*head == NULL || position <= 0) {


printf("Invalid position or empty list.\n");
return;
}

if (position == 1) {
struct Node* temp = *head;

while (temp->next != *head) {


temp = temp->next;
}

newNode->next = *head;
temp->next = newNode;
*head = newNode;
return;
}

struct Node* temp = *head;


int count = 1;

while (count < position - 1 && temp->next != *head) {

Page No
Data Structure (3130702) 230170146053
temp = temp->next;
count++;
}

if (temp->next == *head && count != position - 1) {


printf("Position out of bounds.\n");
free(newNode); // Clean up the memory for the new node
return;
}

newNode->next = temp->next;
temp->next = newNode;
}

void display(struct Node* head) {


if (head == NULL) {
printf("List is empty.\n");
return;
}

struct Node* temp = head;

do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);

printf("(head)\n");
}

int main() {
struct Node* head = NULL;

insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);

printf("Original List: ");


display(head);

insertBeforePosition(&head, 15, 2);


printf("After inserting 15 before position 2: ");
display(head);

Page No
Data Structure (3130702) 230170146053
insertBeforePosition(&head, 5, 1);
printf("After inserting 5 before position 1: ");
display(head);

insertBeforePosition(&head, 25, 5);


printf("After inserting 25 before position 5: ");
display(head);

return 0;
}

Output:

Original List: 10 -> 20 -> 30 -> 40 -> (head)


After inserting 15 before position 2: 10 -> 15 -> 20 -> 30 -> 40 -> (head)
After inserting 5 before position 1: 5 -> 10 -> 15 -> 20 -> 30 -> 40 -> (head)
After inserting 25 before position 5: 5 -> 10 -> 15 -> 20 -> 25 -> 30 -> 40 -> (head)

(c) Delete a first node of the linked list.

Program:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

void insertAtEnd(struct Node** head, int data) {


struct Node* newNode = createNode(data);

if (*head == NULL) {
*head = newNode;
newNode->next = *head;
} else {
struct Node* temp = *head;

Page No
Data Structure (3130702) 230170146053
while (temp->next != *head) {
temp = temp->next;
}

temp->next = newNode;
newNode->next = *head;
}
}

void deleteFirstNode(struct Node** head) {


if (*head == NULL) {
printf("List is empty.\n");
return;
}

if ((*head)->next == *head) {
free(*head);
*head = NULL;
return;
}

struct Node* temp = *head;


while (temp->next != *head) {
temp = temp->next;
}

struct Node* toDelete = *head;


*head = (*head)->next;
temp->next = *head; // Update the last node to point to the new head

free(toDelete); // Free the old head node


}

void display(struct Node* head) {


if (head == NULL) {
printf("List is empty.\n");
return;
}

struct Node* temp = head;

do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);

Page No
Data Structure (3130702) 230170146053
printf("(head)\n");
}

int main() {
struct Node* head = NULL;

insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);

printf("Original List: ");


display(head);

deleteFirstNode(&head);
printf("After deleting first node: ");
display(head);

deleteFirstNode(&head);
printf("After deleting first node again: ");
display(head);

return 0;
}

Output:

Original List: 10 -> 20 -> 30 -> 40 -> (head)


After deleting first node: 20 -> 30 -> 40 -> (head)
After deleting first node again: 30 -> 40 -> (head)

(d) Delete a node after specified position.

Program:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

Page No
Data Structure (3130702) 230170146053
newNode->data = data;
newNode->next = NULL;
return newNode;
}

void insertAtEnd(struct Node** head, int data) {


struct Node* newNode = createNode(data);

if (*head == NULL) {
*head = newNode;
newNode->next = *head;
} else {
struct Node* temp = *head;

while (temp->next != *head) {


temp = temp->next;
}

temp->next = newNode;
newNode->next = *head;
}
}

void deleteNodeAfterPosition(struct Node** head, int position) {


if (*head == NULL) {
printf("List is empty.\n");
return;
}

struct Node* temp = *head;

if ((*head)->next == *head) {
printf("There is only one node in the list.\n");
return;
}

int count = 1;

while (count < position && temp->next != *head) {


temp = temp->next;
count++;
}

if (temp->next == *head) {
printf("Position out of bounds.\n");
return;

Page No
Data Structure (3130702) 230170146053
}

struct Node* toDelete = temp->next;

if (toDelete == *head) {
struct Node* last = *head;

while (last->next != *head) {


last = last->next;
}

*head = (*head)->next;
last->next = *head;
} else {
temp->next = toDelete->next;
}

free(toDelete);
}

void display(struct Node* head) {


if (head == NULL) {
printf("List is empty.\n");
return;
}

struct Node* temp = head;

do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);

printf("(head)\n");
}

int main() {
struct Node* head = NULL;

insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);
insertAtEnd(&head, 50);

Page No
Data Structure (3130702) 230170146053
printf("Original List: ");
display(head);

deleteNodeAfterPosition(&head, 2);
printf("After deleting node after position 2: ");
display(head);
deleteNodeAfterPosition(&head, 4);
printf("After deleting node after position 4: ");
display(head);

return 0;
}

Output:

Original List: 10 -> 20 -> 30 -> 40 -> 50 -> (head)


After deleting node after position 2: 10 -> 20 -> 40 -> 50 -> (head)
After deleting node after position 4: 10 -> 20 -> 40 -> (head)

5.2 Identify widely used application which uses linked list for implementation of its
important feature.
a) Dynamic Memory Allocation:
• Linked lists are used in memory management systems to keep track of free and
allocated memory blocks. They allow efficient allocation and deallocation of memory.
b) Data Structures:
• More complex data structures, such as stacks, queues, and hash tables, often use linked
lists as their underlying implementation due to their dynamic size and ease of
insertion/deletion.
c) Undo Functionality in Software Applications:
• Many text editors and applications implement an undo feature using linked lists, where
each node represents a state of the document, allowing users to traverse back through
previous states.
d) Browser History Management:
• Web browsers use linked lists to maintain a history of visited pages, allowing users to
navigate back and forth through their browsing history efficiently.
e) Implementation of Adjacency List in Graphs:
• Linked lists are commonly used to represent graphs using adjacency lists, enabling
efficient storage and traversal of graph data structures.
f) Music and Video Playlists:
• Media players often implement playlists as linked lists, allowing users to easily add,
remove, or reorder songs and videos.
g) Real-Time Applications:
• In systems requiring real-time data handling, such as task scheduling, linked lists
provide a flexible way to manage and prioritize tasks dynamically.

Page No
Data Structure (3130702) 230170146053
h) Polynomial Arithmetic:
• Linked lists can efficiently represent polynomials, where each node corresponds to a
term, allowing for easy addition, subtraction, and multiplication of polynomials.

Observations:

Dynamic Sizing
Efficiency
Flexibility
Memory Usage

Conclusion:

Linked lists are widely used in various applications due to their flexibility, dynamic sizing,
and efficient memory management capabilities. They form the backbone of many essential data
structures and features in modern software applications, such as dynamic memory allocation,
undo functionality, and browser history management.
Quiz:

(1) What are disadvantages of circular link list?


(2) Differentiate Circular link list and Queue
(3) Which are the operations on circular link list?

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

1. Paul G. Sorenson Publisher-Tata McGraw Hill.

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

Page No
Data Structure (3130702) 230170146053

Experiment No: 6

AIM : Tree

6.1 Write a program which create binary search tree.


6.2 Implement recursive tree traversing methods in-order, pre-order and post-order
traversal.
6.3 Identify widely used applications which use Tree data structure for implementation
of its important feature.

Date: / / 2024

Competency and Practical Skills: Logic building and programming

Relevant CO: CO3, CO5

Objectives: (a) To understand the concepts of Tree


(b) To analyze different algorithms on Tree
(c) To implement various operations on Tree

Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

✓ Operate computer system carefully and responsibly.


✓ Use required lab resources cautiously

Theory:

Binary Search Tree

A binary search tree is a binary tree in which each node possessed a key that satisfy the
following conditions

1. All key (if any) in the left sub tree of the root precedes the key in the root.
2. The key in the root precedes all key (if any) in the right sub tree.
3. The left and right sub tree sub trees of the root are again search trees.

Operations on tree

The most common operations performed on tree structure are that of traversal. This is a procedure
by which each node in the tree is processed exactly once in a systematic manner.

There are three ways of traversing a binary tree.

1. Pre-order Traversal
Page No
Data Structure (3130702) 230170146053
2. In-order Traversal
3. Post-order Traversal
Pre-order

✓ Pre-order traversal of a binary tree is defined as follow


• Process the root node
• Traverse the left sub tree in pre-order
• Traverse the right sub tree in pre-order
✓ If particular sub tree is empty (i.e., node has no left or right descendant) the traversal is
performed by doing nothing, In other words, a null sub tree is considered to be fully
traversed when it is encountered.

In-order

✓ The In-order traversal of a binary tree is given by following steps,


• Traverse the left sub tree in In-order
• Process the root node
• Traverse the right sub tree in In-order

Post-order

✓ The post-order traversal is given by


• Traverse the left sub tree in post-order
• Traverse the right sub tree in post-order
• Process the root node

6.1 Write a program which create binary search tree.

Program:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* left;
struct Node* right;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
Page No
Data Structure (3130702) 230170146053
struct Node* insertNode(struct Node* root, int data) {

if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);
} else if (data > root->data) {
root->right = insertNode(root->right, data);
}
return root;
}

void inorderTraversal(struct Node* root) {


if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}

int main() {
struct Node* root = NULL;
int n, value;

printf("Enter the number of nodes you want to insert: ");


scanf("%d", &n);

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


printf("Enter value for node %d: ", i+1);
scanf("%d", &value);
root = insertNode(root, value);
}

printf("Inorder Traversal of the Binary Search Tree: ");


inorderTraversal(root);
printf("\n");

return 0;
}

Output:

Page No
Data Structure (3130702) 230170146053

Enter the number of nodes you want to insert: 5


Enter value for node 1: 50
Enter value for node 2: 30
Enter value for node 3: 70
Enter value for node 4: 20
Enter value for node 5: 40

Inorder Traversal of the Binary Search Tree: 20 30 40 50 70

6.2 Implement recursive tree traversing methods in-order, preorder and post-order
traversal.

Program:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* left;
struct Node* right;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

struct Node* insertNode(struct Node* root, int data) {


if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);
} else if (data > root->data) {
root->right = insertNode(root->right, data);
}
return root;
}

void inorderTraversal(struct Node* root) {


if (root != NULL) {
inorderTraversal(root->left);
Page No
Data Structure (3130702) 230170146053
printf("%d ", root->data);
inorderTraversal(root->right);
}
}

void preorderTraversal(struct Node* root) {


if (root != NULL) {
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}

void postorderTraversal(struct Node* root) {


if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}
}

int main() {
struct Node* root = NULL;
int n, value;

printf("Enter the number of nodes you want to insert: ");


scanf("%d", &n);

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


printf("Enter value for node %d: ", i + 1);
scanf("%d", &value);
root = insertNode(root, value);
}

printf("\nIn-order Traversal: ");


inorderTraversal(root);
printf("\n");

printf("Pre-order Traversal: ");


preorderTraversal(root);
printf("\n");

printf("Post-order Traversal: ");

Page No
Data Structure (3130702) 230170146053
postorderTraversal(root);
printf("\n");

return 0;
}

Output:

Enter the number of nodes you want to insert: 5


Enter value for node 1: 50
Enter value for node 2: 30
Enter value for node 3: 70
Enter value for node 4: 20
Enter value for node 5: 40

In-order Traversal: 20 30 40 50 70
Pre-order Traversal: 50 30 20 40 70
Post-order Traversal: 20 40 30 70 50

6.3 Identify widely used applications which use Tree data structure for implementation
of its important feature.

a) Binary Search Trees (BST) in Databases:


• BSTs are used in database indexing systems such as B-trees and AVL trees.
b) File Systems:
• Most operating systems (e.g., Windows, Linux) use a tree structure to represent the
hierarchical organization of files and directories. This allows for efficient navigation and
access to files.
c) Expression Trees in Compilers:
• Compilers use expression trees (a type of binary tree) to parse mathematical expressions and
generate machine-level instructions.
d) XML/HTML Document Object Model (DOM):
• Web browsers and parsers represent XML and HTML documents as tree structures (DOM
trees).
e) Trie in Auto-Complete:
• Tries (prefix trees) are used in search engines and text editors for fast retrieval of strings or
prefixes.
f) Routing Algorithms in Networking:
• Tree-based algorithms, such as spanning trees, are used in computer networks to optimize
routing and prevent loops in the network.
g) Artificial Intelligence and Decision Trees:
• Decision trees are commonly used in machine learning for classification and regression tasks.

Observations:

Page No
Data Structure (3130702) 230170146053

Efficiency
Flexibility
Scalability
Hierarchical Nature
Application-specific Optimizations

Conclusion:

Tree data structures play a crucial role in the implementation of many widely used
applications due to their efficiency, flexibility, and hierarchical nature. From databases and file
systems to networking and artificial intelligence, trees provide a foundation for efficient data
organization, retrieval, and manipulation. The versatility of trees enables them to be used in a
variety of fields, from search engines that utilize tries for auto-completion to machine learning
algorithms that rely on decision trees for classification and decision-making tasks. The ability of
trees to scale and adapt to different data types makes them indispensable in modern computing.

Quiz:

(1) Define binary search tree


(2) Explain pre-order, in-order and post order traversal techniques
(3) Which are the applications of binary search tree?

Suggested Reference:

3. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
4. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
5. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
6. http://www.geeksforgeeks.org/data-structures/
7. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

1. Paul G. Sorenson Publisher-Tata McGraw Hill.

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

Page No
Data Structure (3130702) 230170146053

Experiment No: 7

AIM : Graph

7.1 Write a program to perform BFS and DFS on given graph.


7.2 Identify widely used applications which use graphs data structure for implementation
of its important feature.

Date:

Competency and Practical Skills: Logic building and programming

Relevant CO: CO3, CO5

Objectives: (a) To understand the concepts of graphs


(b) To analyze different algorithms on graphs
(c) To implement various operations on graphs

Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

✓ Operate computer system carefully and responsibly.


✓ Use required lab resources cautiously

Theory:

Graph:

A graph G can be defined as a non-empty set of vertices or nodes (V) and a set of edges (E) that
represents the relationship or connection between those nodes. The edges can be defined as a
mapping from E to pairs of elements of V. A graph can be represented as G = (V, E), where V
represents the set of nodes and E represents the set of edges. Each edge of the graph G can be
associated with a pair of nodes of the graph. If an edge X belongs to E and is associated with a pair
of nodes (u, v), where u and v belong to V, then we say that edge X connects node u and node v.

Depth First Search (DFS):

DFS is a graph traversal algorithm that is similar to the preorder traversal of a tree. The traversal
can start from any vertex vi of the graph. Initially, the vertex vi is visited, and then all the adjacent
vertices to vi are traversed recursively using DFS. As a graph can have cycles, we need to avoid
revisiting a node. To achieve this, when a vertex V is visited, it is marked as visited and should not
be selected for traversal again.

Page No
Data Structure (3130702) 230170146053

Breadth First Search (BFS)

• Breadth First Search (BFS) starts from a vertex v0 and marks it as visited. Then, all the
vertices adjacent to v0 are visited next.
• Let the vertices adjacent to v0 be v1, v2, v3, and v4. These vertices are marked as visited.
• All unvisited vertices adjacent to v1, v2, v3, and v4 are visited next.
• The above process continues until all vertices are visited.
• The algorithm for BFS maintains a list of vertices that have been visited but not explored
for adjacent vertices. This list is stored in a queue.
• The queue initially contains the starting vertex.
• In each iteration, a vertex is removed from the queue, and its adjacent vertices, which have
not been visited yet, are added to the queue.
• The algorithm terminates when the queue becomes empty.

7.1 Write a program to perform BFS and DFS on given graph.

Program:
#include <stdio.h>
#include <stdlib.h>

#define MAX 100

struct Node {
int vertex;
struct Node* next;
};

struct Graph {
int numVertices;
struct Node** adjLists;
int* visited;
};
struct Node* createNode(int v) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

struct Graph* createGraph(int vertices) {


struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->numVertices = vertices;

graph->adjLists = (struct Node**)malloc(vertices * sizeof(struct Node*));


graph->visited = (int*)malloc(vertices * sizeof(int));
Page No
Data Structure (3130702) 230170146053

int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}

return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

void BFS(struct Graph* graph, int startVertex) {


int queue[MAX], front = 0, rear = -1;
int i;

graph->visited[startVertex] = 1;
queue[++rear] = startVertex;

printf("BFS Traversal: ");

while (front <= rear) {


int currentVertex = queue[front++];
printf("%d ", currentVertex);

struct Node* temp = graph->adjLists[currentVertex];

while (temp) {
int adjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0) {
queue[++rear] = adjVertex;
graph->visited[adjVertex] = 1;
}
temp = temp->next;
}
}

printf("\n");

Page No
Data Structure (3130702) 230170146053
}

// DFS algorithm
void DFS(struct Graph* graph, int vertex) {
struct Node* adjList = graph->adjLists[vertex];
struct Node* temp = adjList;

graph->visited[vertex] = 1;
printf("%d ", vertex);

while (temp != NULL) {


int connectedVertex = temp->vertex;

if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}

void resetVisited(struct Graph* graph) {


int i;
for (i = 0; i < graph->numVertices; i++) {
graph->visited[i] = 0;
}
}

int main() {
struct Graph* graph = createGraph(6);

addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
addEdge(graph, 3, 5);

BFS(graph, 0);

DFS
resetVisited(graph);

printf("DFS Traversal: ");


DFS(graph, 0);
printf("\n");

Page No
Data Structure (3130702) 230170146053

return 0;
}
Output:

BFS Traversal: 0 1 2 3 4 5
DFS Traversal: 0 1 3 4 5 2

7.2 Identify widely used applications which use graphs data structure for implementation
of its important feature.

1) Social Networks
• Feature: Graph algorithms are used for finding mutual friends, recommending new
connections, and identifying communities within the network.
• Example: Facebook’s “People You May Know” feature is built on graph traversal
algorithms to recommend friends based on mutual connections.
2) Google Maps and GPS Navigation Systems
• Feature: Graph algorithms like Dijkstra's and A* are used to find the shortest path
between locations.
• Example: Google Maps uses graph data structures to calculate the quickest route,
taking into account factors like distance, traffic, and alternate routes.
3) Recommendation Systems
• Feature: These systems use collaborative filtering and content-based filtering
techniques, where users and products are represented as nodes and interactions (e.g.,
purchases, ratings) as edges.
• Example: Netflix recommends movies to users based on their viewing history and the
preferences of similar users, all of which is modeled using a graph.
4) Web Page Ranking (Google's PageRank)
• Feature: Google’s PageRank algorithm is based on graph traversal to rank the
importance of web pages based on their inbound and outbound links.
• Example: PageRank uses the graph structure of the web to determine which pages are
more relevant to a given search query.
5) Computer Networks (Routing Algorithms)
• Feature: Routing algorithms like Open Shortest Path First (OSPF) and Border
Gateway Protocol (BGP) use graphs to find optimal paths for data transmission.
• Example: Routers use graph algorithms to efficiently forward data packets across the
internet by finding the shortest or least congested path.
6) Artificial Intelligence (AI) and Machine Learning (ML)
• Feature: Graph Neural Networks (GNN) and knowledge graphs help in tasks like
natural language processing, recommendation systems, and fraud detection.
• Example: Knowledge graphs are used in semantic search engines like Google Search
to understand user queries in a more meaningful way by connecting related concepts.
7) Transport and Logistics
• Feature: Graph algorithms are used for vehicle routing problems, minimizing costs
and delivery time.
• Example: Amazon uses graph-based optimization to deliver packages efficiently by

Page No
Data Structure (3130702) 230170146053
reducing travel time and fuel consumption.
8) Compiler Design
• Feature: Data-flow analysis, dead code elimination, and instruction scheduling are
graph-based features in modern compilers.
• Example: Compilers build a control flow graph (CFG) to optimize code execution
paths and detect possible optimizations.

Observations:
Complex Relationships
Optimization
Scalability
Flexibility
AI Integration

Conclusion:

Graphs are a foundational data structure in computer science, with applications spanning
across various domains, from social networks to AI. They are invaluable in any scenario where
relationships between data points must be modeled, analyzed, and optimized.

Quiz:

(1) Define Directed Acyclic Graph (DAG).


(2) Differentiate DFS and BFS.
(3) State the applications of graph.

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

1. Paul G. Sorenson Publisher-Tata McGraw Hill.

Rubric-wise marks obtained:

Problem Logic Coding Completeness


Rubrics Q&A Total
Understanding Building (2) Standards and accuracy

Page No
Data Structure (3130702) 230170146053
(2) (2) (2)

Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

Page No
Data Structure (3130702) 230170146053

Experiment No: 8

AIM : Searching

8.1 Write a program to implement Linear Search.


8.2 Write a program to implement Binary Search.
8.3 Identify widely used applications which use Searching technique for implementation
of its important feature.

Date: / /2024

Competency and Practical Skills: Logic building and programming

Relevant CO: CO4, CO5

Objectives: (a) To understand the concepts of Searching


(b) To analyze different algorithms on Searching
(c) To implement various operations on Searching

Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

✓ Operate computer system carefully and responsibly.


✓ Use required lab resources cautiously

Theory:

Linear/Sequential Search

• Linear search, also known as sequential search, is a technique used in computer science to
find a specific value in a list by sequentially checking each of its elements one at a time until
the desired one is found.
• It is the simplest search algorithm and a form of brute-force search. Its worst-case cost is
proportional to the number of elements in the list.

Binary Search

• If we have an array that is sorted, we can use a much more efficient algorithm called Binary
Search.
• In Binary Search, we divide the array into two equal halves and compare the middle element
with the search element.
• If the middle element is equal to the search element, we have found the element and return
its index; otherwise, if the middle element is less than the search element, we look at the
right part of the array, and if the middle element is greater than the search element, we
Page No
Data Structure (3130702) 230170146053

look at the left part of the array.

8.1 Write a program to implement Linear Search.

Program:

#include <stdio.h>

int linearSearch(int arr[], int size, int target) {


for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return the index of the target element
}
}
return -1; // Return -1 if the target is not found
}

int main() {
int n, target, result;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

int arr[n];

printf("Enter the elements of the array:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Enter the element to search for: ");


scanf("%d", &target);

result = linearSearch(arr, n, target);

if (result != -1) {
printf("Element found at index %d\n", result);
} else {
printf("Element not found in the array\n");
}

return 0;
}
Page No
Data Structure (3130702) 230170146053
Output:

Enter the number of elements in the array: 5


Enter the elements of the array:
10 20 30 40 50
Enter the element to search for: 30
Element found at index 2

8.2 Write a program to implement Binary Search.

Program:

#include <stdio.h>

int binarySearch(int arr[], int size, int target) {


int left = 0, right = size - 1;

while (left <= right) {


int mid = left + (right - left) / 2; // Find the middle element

if (arr[mid] == target) {
return mid; // Return the index if the target is found
}

if (arr[mid] < target) {


left = mid + 1;
}

else {
right = mid - 1;
}
}

return -1;
}

int main() {
int n, target, result;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

int arr[n];
Page No
Data Structure (3130702) 230170146053

printf("Enter the sorted elements of the array:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Enter the element to search for: ");


scanf("%d", &target);

result = binarySearch(arr, n, target);

if (result != -1) {
printf("Element found at index %d\n", result);
} else {
printf("Element not found in the array\n");
}

return 0;
}

Output:

Enter the number of elements in the array: 6


Enter the sorted elements of the array:
10 20 30 40 50 60
Enter the element to search for: 40
Element found at index 3

8.3 Identify widely used applications which use Searching technique for implementation
of its important feature.

a) Databases:
Linear search may be used for unsorted data or small datasets where the overhead of
sorting is unnecessary.
b) Search Engines:
• Search engines such as Google employ advanced search algorithms that build upon the
basic principles of search. Binary search is often used in sorting and retrieval, while
more complex algorithms like inverted indexing and ranking systems enhance the
search process.
c) File Systems:
• Hash-based searching is also employed in modern systems to enhance the speed of file
access.
d) Internet Routing Protocols:
• Networking protocols such as OSPF (Open Shortest Path First) use search techniques

Page No
Data Structure (3130702) 230170146053
to find the shortest path in routing tables. Binary search techniques, among others, are
used to optimize routing decisions in hierarchical networks.
e) Library Systems:
• In library management systems, books are stored in sorted order (by author, title, or
category). Binary search is used to efficiently search for a book among millions of
entries.
f) Spell Checkers and Auto-Correct:
• Spell-check and auto-correct algorithms use searching techniques like trie-based
search and binary search to quickly look up words in dictionaries or suggest
corrections for misspelled words.
g) Gaming:
• Games with large environments or inventories use searching techniques to locate
items, objects, or paths. For example, games with inventories use search techniques to
manage item retrieval or player movement optimization using pathfinding algorithms.
h) Artificial Intelligence:
• In AI, search algorithms are used to explore decision trees, optimize pathfinding, and
retrieve relevant data. For instance, binary search is applied in various AI algorithms
to optimize performance.
i) E-commerce Websites:
• E-commerce platforms like Amazon use binary search and other advanced algorithms
to sort and search through large catalogs of products. When a user searches for an
item, the platform uses searching techniques to efficiently match queries to product
entries.

Observations:

Efficiency
Scalability
Flexibility
Applicability

Conclusion:

Searching techniques are fundamental to many widely used applications, from databases and
search engines to file systems and e-commerce platforms. Their efficiency and scalability
make them indispensable in environments where data retrieval is crucial. While linear search
is simple and effective for small, unsorted datasets, binary search is preferred for larger,
sorted datasets due to its logarithmic efficiency. In addition to basic searching, advanced
algorithms that build on these techniques are employed to handle large-scale data, complex
queries, and real-time systems. As technology evolves, searching techniques continue to play
a key role in optimizing performance and improving user experience in various applications.

Quiz:

(1) List out searching algorithms

Page No
Data Structure (3130702) 230170146053
(2) Differentiate sequential search and binary search
(3) Which are the applications of binary search algorithm?

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

2. Paul G. Sorenson Publisher-Tata McGraw Hill.

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

Page No
Data Structure (3130702) 230170146053

Experiment No: 9

AIM : Sorting

9.1 Write a program to implement Quick Sort


9.2 Write a program to implement Merge Sort
9.3 Write a program to implement Bubble Sort
9.4 Identify widely used applications which use Sorting technique for implementation
of its important feature.

Date: / /2024

Competency and Practical Skills: Logic building and programming

Relevant CO: CO4, CO5

Objectives: (a) To understand the concepts of Sorting


(b) To analyze different algorithms on Sorting
(c) To implement various operations on Sorting

Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

✓ Operate computer system carefully and responsibly.


✓ Use required lab resources cautiously

Theory:

Bubble sort

Bubble sort, also known as sinking sort, is a comparison-based sorting algorithm. It works by
repeatedly scanning through the list to be sorted, comparing adjacent elements and swapping them
if they are not in the correct order. In each pass through the list, the largest element bubbles up to
the top. The algorithm repeats these processes until no more swaps are needed, indicating that the
list is sorted. Although it is simple to understand and implement, bubble sort has a worst-case and
average time complexity of O(n^2), making it too slow for large inputs. Insertion sort is a more
efficient alternative for small lists.

Merge Sort

• The merge sort algorithm is based on the classical divide-and-conquer paradigm. It operates
as follows:

Page No
Data Structure (3130702) 230170146053
▪ DIVIDE: Partition the n-element sequence to be sorted into two sub sequences of
n/2 elements each.
▪ CONQUER: Sort the two sub sequences recursively using the merge sort.

▪ COMBINE: Merge the two sorted sub sequences of size n/2 each to produce the
sorted sequence consisting of n elements.

Quick Sort

Quicksort is currently the fastest known sorting algorithm and often the most practical choice for
sorting, with an average expected running time of O(n log(n)). Its operation consists of the following
steps:
• Pick an element from the array, known as a pivot.
• Reorder the array so that all elements with values less than the pivot are placed before it,
while all elements with values greater than the pivot come after it (elements with equal
values can go either way). This operation is called partitioning, and at the end of it, the pivot
is in its final position.
• Recursively apply the above steps to the sub-arrays of elements with smaller and greater
values, respectively. Quicksort, like merge sort, is a divide-and-conquer recursive
algorithm.
• The basic divide-and-conquer process for sorting a sub array is given in the following three
easy steps:
▪ Divide
▪ Conquer
▪ Combine

9.1 Write a program to implement Quick Sort

Program:
#include <stdio.h>

void swap(int* a, int* b) {


int temp = *a;
*a = *b;
*b = temp;
}

int partition(int arr[], int low, int high) {


int pivot = arr[high]; // Choosing the last element as pivot
int i = (low - 1); // Index of smaller element

for (int j = low; j < high; j++) {


if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]); // Swap the elements
}

Page No
Data Structure (3130702) 230170146053
}
swap(&arr[i + 1], &arr[high]); // Swap pivot with the element at index i+1
return (i + 1); // Return the partition index
}

void quickSort(int arr[], int low, int high) {


if (low < high) {

int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);


quickSort(arr, pi + 1, high);
}
}

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int n;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

int arr[n];

printf("Enter the elements of the array:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

quickSort(arr, 0, n - 1);

printf("Sorted array: ");


printArray(arr, n);

return 0;
}

Page No
Data Structure (3130702) 230170146053

Output:

Enter the number of elements in the array: 5


Enter the elements of the array:
34 7 23 32 5
Sorted array: 5 7 23 32 34

9.2 Write a program to implement Merge Sort

Program:
#include <stdio.h>

void merge(int arr[], int left, int mid, int right) {


int i, j, k;
int n1 = mid - left + 1; // Size of the left subarray
int n2 = right - mid; // Size of the right subarray

int L[n1], R[n2];

for (i = 0; i < n1; i++)


L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

i = 0; // Initial index of the first subarray


j = 0; // Initial index of the second subarray
k = left; // Initial index of merged subarray

while (i < n1 && j < n2) {


if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = L[i];
i++;
Page No
Data Structure (3130702) 230170146053
k++;
}

while (j < n2) {


arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int left, int right) {


if (left < right) {
// Find the middle point
int mid = left + (right - left) / 2;

mergeSort(arr, left, mid);


mergeSort(arr, mid + 1, right);

merge(arr, left, mid, right);


}
}

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int n;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

int arr[n];

printf("Enter the elements of the array:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

Page No
Data Structure (3130702) 230170146053

mergeSort(arr, 0, n - 1);

printf("Sorted array: ");


printArray(arr, n);

return 0;
}

Output:

Enter the number of elements in the array: 5


Enter the elements of the array:
34 7 23 32 5
Sorted array: 5 7 23 32 34

9.3 Write a program to implement Bubble Sort

Program:

#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
int swapped;

for (i = 0; i < n - 1; i++) {


swapped = 0; // Initialize swapped flag

for (j = 0; j < n - i - 1; j++) {


if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1; // Set swapped flag
}
}
if (swapped == 0) {
break;
}
}
}

void printArray(int arr[], int size) {


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

Page No
Data Structure (3130702) 230170146053
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int n;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

int arr[n];

printf("Enter the elements of the array:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
bubbleSort(arr, n);

printf("Sorted array: ");


printArray(arr, n);

return 0;
}

Output:

Enter the number of elements in the array: 5


Enter the elements of the array:
64 34 25 12 22
Sorted array: 12 22 25 34 64

9.4 Identify widely used applications which use Sorting technique for implementation
of its important feature.

a) Database Management Systems:


• Sorting algorithms are employed in indexing to speed up search operations.
b) Search Engines:
• Search engines sort search results based on relevance, popularity, and various ranking
factors. Efficient sorting algorithms ensure quick retrieval of the most relevant results.
c) E-commerce Platforms:
• E-commerce sites like Amazon use sorting techniques to display products based on
user preferences, such as price, ratings, or popularity. Users can sort product listings
to enhance their shopping experience.
d) Social Media:
• Platforms like Facebook and Instagram sort posts in users' feeds based on engagement

Page No
Data Structure (3130702) 230170146053
metrics (likes, shares, comments) to prioritize content that is likely to interest users.
e) Data Analytics and Reporting:
• Sorting is essential in data analysis tools for organizing datasets, making it easier to
identify trends, averages, or outliers. Reports often present data sorted by specific
metrics for clarity.
f) Computer Graphics:
• In rendering processes, sorting techniques are used to handle overlapping objects and
manage depth ordering, ensuring proper rendering of scenes.
g) Machine Learning and Data Preprocessing:
• Many machine learning algorithms require sorted data for training models effectively,
particularly in decision tree algorithms and when calculating nearest neighbors.
h) Library Management Systems:
• Libraries use sorting to organize books by title, author, or genre, facilitating easier
search and retrieval for patrons.
i) Networking:
• Networking applications often need to sort routing tables and manage connections
based on various criteria, such as latency or bandwidth.

Observations:

• Efficiency
• Scalability
• Usability
• Versatility

Conclusion:

Sorting techniques play a vital role in many widely used applications, enhancing
performance, usability, and efficiency. From database management and e-commerce platforms
to data analysis and machine learning, the ability to organize data effectively is crucial for
modern software systems.

Quiz:

(1) Define sorting


(2) What is divide-and-conquer strategy for sorting?
(3) Which is the best suitable sorting algorithm as per its execution time?

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.

Page No
Data Structure (3130702) 230170146053
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

1. Paul G. Sorenson Publisher-Tata McGraw Hill

Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

Page No
Data Structure (3130702) 230170146053
Experiment No: 10

AIM : Hashing and File Structure

10.1 Write a program to create hash table and handle the collision using linear probing.
10.2 Write a program to demonstrate the file primitives such as fopen, fclose, fprintf.
10.3 Identify widely used applications which use Hashing technique for implementation of
its important feature.

Date:

Competency and Practical Skills: Logic building and programming

Relevant CO: CO4, CO5

Objectives: (a) To understand the concepts of Hashing techniques


(b) To implement various file operations

Equipment/Instruments: Computer System with turbo C/C++

Safety and necessary Precautions:

✓ Operate computer system carefully and responsibly.


✓ Use required lab resources cautiously

Theory:

Hashing

Hashing is a method used to map a large number of data items to a smaller table by utilizing a
hashing function. This technique transforms a range of key values into a range of indexes of an
array.There are two different forms of hashing.

1. Open hashing or external hashing: Open or external hashing, allows records to be stored
in unlimited space (could be a hard disk). It places no limitation on the size of the tables.
2. Close hashing or internal hashing: Closed or internal hashing, uses a fixed space for
storage and thus limits the size of hash table.

Hashing Functions

Characteristics of a Good Hash Function


• A good hash function avoids collisions.
• A good hash function tends to spread keys evenly in the array.
• A good hash function is easy to compute.

Page No
Data Structure (3130702) 230170146053
Different hashing functions

1. Division-Method
2. Folding Method
3. Algebraic Coding
4. Multiplicative Hashing
5. Digit Analysis
6. Mid-square Methods
7. Length Dependent Method

Collision Resolution Strategies

• Collision resolution is the main problem in hashing.


• If the element to be inserted is mapped to the same location, where an element is already
inserted then we have a collision and it must be resolved.
• There are several strategies for collision resolution. The most commonly used are :
1. Separate chaining - used with open hashing
2. Open addressing - used with closed hashing

File

In computing, a file is a group of records, where each record comprises one or more fields that have
the same sequence. Typically, each field has a predetermined length.

Different file organizations

1. Sequential files
2. Direct files
3. Index files
4. Indexed Sequential files
5. Relative files

Primitive Operations on a File

1. Creation
2. Insertion
3. Deletion
4. Updation
5. Reading
6. Searching

Page No
Data Structure (3130702) 230170146053

10.1 Write a program to create hash table and handle the collision using linear probing.

Program:

#include <stdio.h>
#include <stdlib.h>

#define TABLE_SIZE 10

struct HashTableEntry {
int key;
int value;
};

void initializeTable(struct HashTableEntry table[]) {


for (int i = 0; i < TABLE_SIZE; i++) {
table[i].key = -1; // -1 indicates that the slot is empty
table[i].value = 0;
}
}

int hashFunction(int key) {


return key % TABLE_SIZE;
}

void insert(struct HashTableEntry table[], int key, int value) {


int index = hashFunction(key);
int originalIndex = index;

while (table[index].key != -1 && table[index].key != key) {


index = (index + 1) % TABLE_SIZE;
if (index == originalIndex) {
printf("Hash table is full!\n");
return;
}
}

table[index].key = key;
table[index].value = value;
}

int search(struct HashTableEntry table[], int key) {


int index = hashFunction(key);
Page No
Data Structure (3130702) 230170146053
int originalIndex = index;

while (table[index].key != -1) {


if (table[index].key == key) {
return table[index].value;
}
index = (index + 1) % TABLE_SIZE;
if (index == originalIndex) {
break;
}
}

return -1; // Key not found


}
void displayTable(struct HashTableEntry table[]) {
printf("Index\tKey\tValue\n");
for (int i = 0; i < TABLE_SIZE; i++) {
if (table[i].key != -1) {
printf("%d\t%d\t%d\n", i, table[i].key, table[i].value);
} else {
printf("%d\t--\t--\n", i);
}
}
}

int main() {
struct HashTableEntry hashTable[TABLE_SIZE];
initializeTable(hashTable);

int choice, key, value;


while (1) {
printf("\n1. Insert\n2. Search\n3. Display\n4. Exit\nEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter key: ");
scanf("%d", &key);
printf("Enter value: ");
scanf("%d", &value);
insert(hashTable, key, value);
break;

case 2:
printf("Enter key to search: ");
scanf("%d", &key);

Page No
Data Structure (3130702) 230170146053
value = search(hashTable, key);
if (value != -1) {
printf("Key found with value: %d\n", value);
} else {
printf("Key not found!\n");
}
break;

case 3:
displayTable(hashTable);
break;

case 4:
exit(0);

default:
printf("Invalid choice!\n");
}
}

return 0;
}

Output:

1. Insert
2. Search
3. Display
4. Exit
Enter your choice: 1
Enter key: 12
Enter value: 100

1. Insert
2. Search
3. Display
4. Exit
Enter your choice: 1
Enter key: 22
Enter value: 200

1. Insert
2. Search
3. Display
4. Exit
Enter your choice: 3

Page No
Data Structure (3130702) 230170146053
Index Key Value
0 -- --
1 -- --
2 -- --
3 12 100
4 22 200
5 -- --
6 -- --
7 -- --
8 -- --
9 -- --

1. Insert
2. Search
3. Display
4. Exit
Enter your choice: 2
Enter key to search: 12
Key found with value: 100

10.2 Write a program to demonstrate the file primitives such as fopen, fclose, fprintf.

Program:

#include <stdio.h>
#include <stdlib.h>

int main() {

FILE *filePtr;

filePtr = fopen("example.txt", "w");

if (filePtr == NULL) {
printf("Error! Could not open file.\n");
exit(1); // Exit if fopen() failed
}

fprintf(filePtr, "This is an example of file I/O in C.\n");


fprintf(filePtr, "Using fprintf to write formatted data to the file.\n");
fprintf(filePtr, "You can write multiple lines using fprintf.\n");

fclose(filePtr);

Page No
Data Structure (3130702) 230170146053
printf("Data successfully written to 'example.txt'.\n");

return 0;
}

Output:

Data successfully written to 'example.txt'.

10.3 Identify widely used applications which use Hashing technique for implementation of
its important feature.

1) Databases
• Application: Hashing is used in database indexing to quickly retrieve data without
scanning entire tables.
• Feature: Hash tables are used to index rows for fast lookups, especially in large
datasets.
2) Cryptography
• Application: Hash functions are a cornerstone of cryptography, where they are used
to ensure data integrity and generate digital signatures.
• Feature: Cryptographic hash functions (e.g., SHA-256, MD5) create fixed-length
outputs that are virtually unique, even for slightly different inputs.
3) Password Storage
• Application: Hashing is widely used to securely store user passwords in databases.
• Feature: Passwords are hashed before storage so that even if a database is
compromised, attackers cannot easily recover the original passwords.
4) Caching Systems
• Application: Hashing is used in caching systems like Redis and Memcached to store
and retrieve frequently used data quickly.
• Feature: Hashing allows mapping of cached objects to specific keys for rapid access,
reducing the load on primary data stores.
5) Compiler Design
• Application: Compilers use hashing for symbol tables, which store identifiers such as
variable names and function names for fast lookups.
• Feature: A hash table allows quick access to variables and functions when compiling
the code, improving the speed of the compilation process.
6) Data Deduplication
• Application: Hashing is used in data deduplication to identify and eliminate duplicate
files or blocks of data.
• Feature: Hashes of files or blocks are compared, and if two hashes match, the system
identifies the data as a duplicate.
7) Load Balancing
• Application: Hashing is used in load balancing algorithms to distribute tasks or
requests evenly across multiple servers.
• Feature: Consistent hashing ensures that requests for a specific resource are always
directed to the same server, optimizing resource usage.
8) File Systems
Page No
Data Structure (3130702) 230170146053
• Application: File systems use hashing to locate file blocks and manage directories
efficiently.
• Feature: A hash table can map file names or file blocks to their locations on disk for
faster file access.
9) Blockchain and Cryptocurrency
• Application: Hashing is essential for verifying transactions and securing data in
blockchain and cryptocurrencies like Bitcoin and Ethereum.
• Feature: Hashing ensures that each block of data in the blockchain is uniquely
identified and secure, making it resistant to tampering.
Observations:

Efficiency
Security
Scalability
Storage Optimization
Robustness

Conclusion:

Hashing is a versatile technique with widespread applications across multiple domains,


from ensuring data security to optimizing resource allocation. Its ability to provide quick access,
data integrity, and security makes it indispensable in modern computing.

Quiz:

(1) What is internal hashing and external hashing?


(2) Explain linear probing.
(3) Which are primitive operations on file?

Suggested Reference:

1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G.


Sorenson Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms

References used by the students:

1. Paul G. Sorenson Publisher-Tata McGraw Hill

Page No
Data Structure (3130702) 230170146053
Rubric-wise marks obtained:

Problem Coding Completeness


Logic
Understanding Standards and accuracy Q&A
Rubrics Building (2) Total
(2) (2) (2)
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)

Marks

Page No

You might also like