Data Structures Overview and C Program
Data Structures Overview and C Program
DATA STRUCTURES
Data Structures:
The logical or mathematical model of a particular organization of data is called
data structures. Data structures is the study of logical relationship existing between
individual data elements, the way the data is organized in the memory and the efficient
way of storing, accessing and manipulating the data elements.
Choice of a particular data model depends on two considerations: it must be rich
enough in structure to mirror the actual relationships of the data in the real world. On
the other hand, the structure should be simple enough that one can effectively process
the data when necessary.
Data Structures can be classified as:
➢ Primitive data structures
➢ Non-Primitive data structures.
• Primitive data structures are the basic data structures that can be directly
manipulated/operated by machine instructions. Some of these are character,
integer, real, pointers etc.
• Non-primitive data structures are derived from primitive data structures, they
cannot be directly manipulated/operated by machine instructions, and these are
group of homogeneous or heterogeneous data items. Some of these are Arrays,
stacks, queues, trees, graphs etc.
Data structures are also classified as
➢ Linear data structures
➢ Non-Linear data structures.
In the Linear data structures processing of data items is possible in linear fashion, i.e.,
data can be processed one by one sequentially.
Example of such data structures are: Array, Linked list, Stacks, Queues
A data structure in which insertion and deletion is not possible in a linear fashion is
called as nonlinear data structure. i.e., which does not show the relationship of logical
adjacency between the elements is called as non-linear data structure. Such as trees,
graphs and files.
Data structure operations:
The particular data structures that one chooses for a given situation depends largely on
the frequency with which specific operations are performed. The following operations
play major role in the processing of data.
i) Traversing.
ii) Searching.
iii) Inserting.
iv) Deleting.
v) Sorting.
vi) Merging
STACKS:
A stack is an ordered collection of items into which new items may be inserted and
from which items may be deleted at the same end, called the TOP of the stack. A stack
is a non-primitive linear data structure. As all the insertion and deletion are done from
the same end, the first element inserted into the stack is the last element deleted from
the stack and the last element inserted into the stack is the first element to be deleted.
Therefore, the stack is called Last-In First-Out (LIFO) data structure.
QUEUES:
A queue is a non-primitive linear data structure. Where the operation on the queue is
based on First-In-First- Out FIFO process — the first element in the queue will be the
first one out. This is equivalent to the requirement that whenever an element is added,
all elements that were added before have to be removed before the new element can be
removed.
For inserting elements into the queue are done from the rear end and deletion is done
from the front end, we use external pointers called as rear and front to keep track of the
status of the queue. During insertion, Queue Overflow condition has to be checked.
Likewise during deletion, Queue Underflow condition is checked.
LINKED LIST:
Disadvantages of static/sequential allocation technique:
1) If an item has to be deleted then all the following items will have to be moved by
one allocation. Wastage of time.
2) Inefficient memory utilization.
3) If no consecutive memory (free) is available, execution is not possible.
Linear Linked Lists Types of Linked lists:
1) Single Linked lists
2) Circular Single Linked Lists
GRAPH:
Definition: A Graph G consists of two sets, V and E. V is a finite set of vertices. E is a set of
edges or pair of vertices.
Two types of graphs:
➢ Undirected Graph
➢ Directed Graph
Undirected Graph: In undirected graph the pair of vertices representing any edge is
unordered. Thus the pairs (u,v)and (v,u) represent the same edge.
Directed graph: In a directed graph each edge is represented by a directed pair , u is the tail
and v is the head of the edge. Therefore and represent two different edges.
Graph representation can be done using adjacency matrix.
➢ Adjacency matrix: Adjacency matrix is a two dimensional n x n array a, with the
property that a[i][j]=1 iff the edge (i,j) is in E(G). a[i][j]=0 if there is no such edge in
G.
➢ Connectivity of the graph: A graph is said to be connected iff for every pair of
distinct vertices u and v , there is a path from u to v.
➢ Path: A path from vertex u to v in a graph is a sequence of vertices u, i1 , i2 …… ik ,
v such that (u, i1), (i1 , i2) ……… (ik , v) are the edges in G.
Graph traversal can be done in two ways:
➢ depth first search(dfs) and
➢ breadth first search (bfs).
• Hashing: Hashing is a process of generating key or keys from a string of text using a
mathematical function called hash function. Hashing is a key-to-address mapping
process.
• Hash Table: In hashing the dictionary pairs are stored in a table called hash table.
Hash tables are partitioned into buckets, buckets consists of s slots , each slot is
capable of holding one dictionary pair.
• Hash function: A hash function maps a key into a bucket in the hash table. Most
commonly used hash function is,
h ( k ) = k % D where,
k is the key
D is Max size of hash table.
PROGRAM 1
Develop a Program in C for the following:
a) Declare a calendar as an array of 7 elements (A dynamically Created array) to
represent 7 days of a week. Each Element of the array is a structure having three
fields. The first field is the name of the Day (A dynamically allocated String), The
second field is the date of the Day (A integer), the third field is the description of the
activity for a particular day (A dynamically allocated String).
b) Write functions create(), read() and display(); to create the calendar, to read the
data from the keyboard and to print weeks activity details report on screen.
Objective:
To revise the useful concept of programming prerequisite which will be useful for future lessons.
Structures, union, pointers, 1D array etc. are covered in this lab.
Brief Theory:
Structures: A structure is a user defined data type in C/C++. A structure creates a data type that can be
used to group items of possibly different types into a single type. key word is used to create a
structure. Syntax of structure:
Struct strcture_name
{
datatype member1;
datatype member1;
...
datatype member1;
};
Problems on:
1. Basic C program using loops, structure.
2. Programs on unions, 1D array.
3. To design a small database type application using structure, pointer, array and dynamic memory
allocation.
Observations/Outcome:
1. Develop the understanding of data structure and its types.
2. Ability to use various data structures for solving unseen problems.
3. Understand the use of appropriate data structure to solve real world problems.
SOURCE CODE
#include <stdio.h>
#include <stdlib.h>
// Function to read data from the keyboard and create the calendar
void read(struct Day * calendar, int size)
{
for (int i = 0; i < size; i++)
{
printf("Enter details for Day %d:\n", i + 1);
create( & calendar[i]);
}
}
// Function to display the calendar
void display(struct Day * calendar, int size)
{
printf("\nWeek's Activity Details:\n");
for (int i = 0; i < size; i++)
{
printf("Day %d:\n", i + 1);
printf("Day Name: %s\n", calendar[i].dayName);
printf("Date: %d\n", calendar[i].date);
printf("Activity: %s\n", calendar[i].activity);
printf("\n");
}
}
}
}
int main()
{
int size;
printf("Enter the number of days in the week:");
scanf("%d", & size);
return 0;
}
OUTPUT:
Enter the number of days in the week: 7
Enter details for Day 1:
Enter the day name: Sunday
Enter the date: 1
Enter the activity for the day: Learning
Enter details for Day 2:
Enter the day name: Monday
Enter the date: 2
Enter the activity for the day: Coding
Enter details for Day 3:
Enter the day name: Tuesday
Enter the date: 3
Enter the activity for the day: Testing
Enter details for Day 4:
Enter the day name: Wednesday
Enter the date: 4
Enter the activity for the day: Debugging
Enter details for Day 5:
Enter the day name: Thrusday
Enter the date: 5
Enter the activity for the day: Publishing
Enter details for Day 6:
Enter the day name: Friday
Enter the date: 6
Enter the activity for the day: Marketing
Enter details for Day 7:
Enter the day name: Saturday
Enter the date: 7
Enter the activity for the day: Earning
PROGRAM 2
Develop a Program in C for the following operations on Strings.
a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP)
b. Perform Pattern Matching Operation: Find and Replace all occurrences of PAT in
STR with REP if PAT exists in STR. Report suitable messages in case PAT does not
exist in STR.
Support the program with functions for each of the above operations. Don't use Built-in
functions.
Objectives:
To revise the useful concept of programming prerequisite which will be useful for future lessons.
Strings and operations on strings are are covered in this lab.
Brief theory:
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a
null-terminated string contains the characters that comprise the string followed by a null. The
following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than
the number of characters in the word "Hello." char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows:
char greeting[] = "Hello";
C language supports a wide range of built-in functions that manipulate null-terminated.strings as
follows:
• strcpy(s1, s2); Copies string s2 into string s1.
• strcat(s1, s2); Concatenates string s2 onto the end of string s1.
• strlen(s1); Returns the length of string s1.
• strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1s2.
• strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
• strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
Problems on:
1. Basic C program using strings
2. Programs on string, pattern match
Observations/Outcome:
1. Develop the understanding of strings and operations on strings.
2. Understand the use of appropriate data structure to solve real world problems.
Algorithm:
Step 1: Start.
Step 2: Read main string STR, pattern string PAT and replace string REP.
Step 3: Search / find the pattern string PAT in the main string STR.
Step 4: if PAT is found then replace all occurrences of PAT in main string STR with REP string.
Step 5: if PAT is not found give a suitable error message.
Step 6: Stop.
SOURCE CODE:
#include<stdio.h>
char str[50], pat[20], rep[20], res[50];
int c = 0, m = 0, i = 0, j = 0, k, flag = 0;
void stringmatch()
{
while (str[c] != '\0')
{
if (str[m] == pat[i])
{
i++;
m++;
if (pat[i] == '\0')
{
flag = 1;
for (k = 0; rep[k] != '\0'; k++, j++)
{
res[j] = rep[k];
}
i = 0;
c = m;
}
}
else
{
res[j] = str[c];
j++;
c++;
m = c;
i = 0;
}
}
res[j] = '\0';
}
void main()
{
printf("Enter the main string:");
gets(str);
printf("\nEnter the pat string:");
gets(pat);
printf("\nEnter the replace string:");
gets(rep);
printf("\nThe string before pattern match is:\n %s", str);
stringmatch();
if (flag == 1)
printf("\nThe string after pattern match and replace is: \n %s ", res);
else
printf("\nPattern string is not found");
}
OUTPUT1:
Enter the main string:Designed by vtucode
Enter the pat string:vtucode
Enter the replace string:Braham
OUTPUT2:
Enter the main string:Designed by Developer
Enter the pat string:vtucode
Enter the replace string:Braham
PROGRAM 3
Develop a menu driven Program in C for the following operations on STACK of Integers
(Array Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
d. Demonstrate Overflow and Underflow situations on Stack
e. Display the status of Stack
f. Exit
Support the program with appropriate functions for each of the above operations.
Objectives:
Learn about Stack, stack oprations are covered in this lab.
Brief Theory:
A stack is an abstract data type (ADT), commonly used in most programming languages. It is named
stack as it behaves like a real-world stack.
A real-world stack allows operations at one end only. For example, we can place or remove a card or
plate from top of the stack only. Likewise, Stack ADT allows all data operations at one end only. At
any given time, we can only access the top element of a stack. This feature makes it LIFO data
structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last
is accessed first. In stack terminology, insertion operation is called PUSH operation and removal
operation is called POP operation.
Basic Operations:
• push() - pushing (storing) an element on the stack.
• pop() -removing (accessing) an element from the stack. To use a stack efficiently we need to check
status of stack as well. For the same purpose, the following functionality is added to stacks;
• peek() − get the top data element of the stack, without removing it.
• isFull() − check if stack is full.
• isEmpty() − check if stack is empty.
Problems on:
1. Basic C program using stacks
2. Palindrome function implementation using stack.
Observations/Outcome:
1. Develop the understanding of stack operations
2. Understand the use of appropriate data structure to solve real world problems.
ALGORITHM:
Step 1: Start.
Step 2: Initialize stack size MAX and top of stack -1.
Step 3: Push integer element on to stack and display the contents of the stack. if stack is full give a
message as „Stack is Overflow‟.
Step 4: Pop element from stack along with display the stack contents. if stack is empty give a message
as „Stack is Underflow‟.
Step 5: Check whether the stack contents are Palindrome or not.
Step 6: Stop.
SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
#define MAX 3 //you can change this size according to your requirement
int s[MAX];
int top = -1;
void push(int item);
int pop();
void palindrome();
void display();
void main()
{
int choice, item;
while (1)
{
printf("\n\n\n\n~~~~~~Menu~~~~~~ : ");
printf("\n=>1.Push an Element to Stack and Overflow demo ");
printf("\n=>2.Pop an Element from Stack and Underflow demo");
printf("\n=>3.Palindrome demo ");
printf("\n=>4.Display ");
printf("\n=>5.Exit");
printf("\nEnter your choice: ");
scanf("%d", & choice);
switch (choice)
{
case 1:
printf("\nEnter an element to be pushed: ");
scanf("%d", & item);
push(item);
break;
case 2:
item = pop();
if (item != -1)
printf("\nElement popped is: %d", item);
break;
case 3:
palindrome();
break;
case 4:
display();
break;
case 5:
exit(1);
default:
printf("\nPlease enter valid choice ");
break;
}
}
}
int pop()
{
int item;
if (top == -1)
{
printf("\n~~~~Stack underflow~~~~");
return -1;
}
item = s[top];
top = top - 1;
return item;
}
void display()
{
int i;
if (top == -1)
{
printf("\n~~~~Stack is empty~~~~");
return;
}
printf("\nStack elements are:\n ");
for (i = top; i >= 0; i--)
printf("| %d |\n", s[i]);
}
void palindrome()
{
int flag = 1, i;
printf("\nStack content are:\n");
for (i = top; i >= 0; i--)
printf("| %d |\n", s[i]);printf("\nReverse of stack content are:\n");
for (i = 0; i <= top; i++)
printf("| %d |\n", s[i]);
for (i = 0; i <= top / 2; i++)
{
if (s[i] != s[top - i])
{
flag = 0;
break;
}
}
if (flag == 1)
{
OUTPUT:
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 11
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 12
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 13
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 1
Enter an element to be pushed: 14
~~~~Stack overflow~~~~
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 4
Stack elements are:
| 13 |
| 12 |
| 11 |
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 2
Element popped is: 13
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 4
Stack elements are:
| 12 |
| 11 |
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 2
Element popped is: 12
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
Enter your choice: 2
Element popped is: 11
~~~~~~Menu~~~~~~ :
=>1.Push an Element to Stack and Overflow demo
=>2.Pop an Element from Stack and Underflow demo
=>3.Palindrome demo
=>4.Display
=>5.Exit
PROGRAM 4
Develop a Program in C for converting an Infix Expression to Postfix Expression. Program
should support for both parenthesized and free parenthesized expressions with the operators: +,
-, *, /, % (Remainder), ^ (Power) and alphanumeric operands.
ALGORITHM:
Step 1: Start.
Step 2: Read an infix expression with parenthesis and without parenthesis.
Step 3: convert the infix expression to postfix expression. Step 4: Stop
SOURCE CODE
#include<stdio.h>
void infix_to_postfix();
void push(char);
char pop();
int priority(char);
char infix[30], postfix[30],stack[30];
int top=-1;
void main()
{
printf("Enter the valid Infix expression \n");
scanf("%s",infix);
infix_to_postfix();
printf("\n Infix expression : %s",infix);
printf("\n Postfix expression : %s\n",postfix);
}
OUTPUT:
Sample Output 1
Enter the valid Infix expression
(a+b)*c/d^5%1
Infix expression: (a+b)*c/d^5%1
Postfix expression: ab+c*d5^/1%
Sample Output 2
Enter the valid Infix expression
(a+(b-c)*d)
Infix expression: (a+(b-c)*d)
Postfix expression: abc-d*+
PROGRAM 5
Develop a Program in C for the following Stack Applications a. Evaluation of Suffix
expression with single digit operands and operators: +, -, *, /, %, ^ b. Solving Tower of Hanoi
problem with n disks
Next character scanned is "*", which is an operator. Thus, we pop the top two elements from
the stack and perform the "*" operation with the two operands. The second operand will be
the first element that is popped.
The value of the expression(2*3) that has been evaluated(6) is pushed into the stack.
Next character scanned is "+", which is an operator. Thus, we pop the top two elements from
the stack and perform the "+" operation with the two operands. The second operand will be
the first element that is popped.
The value of the expression(1+6) that has been evaluated(7) is pushed into the stack.
Next character scanned is "-", which is an operator. Thus, we pop the top two elements from
the stack and perform the "-" operation with the two operands. The second operand will be the
first element that is popped.
The value of the expression (7-4) that has been evaluated(3) is pushed into the stack. Now,
since all the characters are scanned, the remaining element in the stack (there will be only one
element in the stack) will be returned. End result: Postfix String:123*+4- Result: 3
ALGORITHM:
Step 1: Start.
Step 2: Read N number of discs.
Step 3: Move all the discs from source to destination by using temp rod.
Step 4: Stop.
#include<stdio.h>
#include<math.h>
void push(float);
float pop();
void evaluate(char[]);
float stack[20];
int top=-1;
void main()
{
int choice,n;
char postfix[100];
while(1) // infinate loop for menu
{
printf("\n STACK APPLICATIONS");
printf("\n Enter your Choice: ");
printf("\n 1. Evaluation of postfix expression with
single digit operands and operators");
printf("\n 2. Solving Tower of Hanoi problem with N
disks");
printf("\n 3. Exit \n");
scanf("%d", &choice);
switch(choice)
{
case 1 : printf("Enter a valid postfix
expression\n");
scanf("%s",postfix);
evaluate(postfix);
break;
case 2 : printf("\n Enter the number of
discs:\n");
scanf("%d",&n);
tower(n,'A','C','B');
break;
case '/':op2=pop();
op1=pop();
if(op2==0)
{
printf("Division by zero
Error\n");
return;
}
res=op1/op2;
push(res);
break;
case '%': op2=pop();
op1=pop();
if(op2==0)
{
printf("Division by zero
Error\n");
return;
}
res=(int)op1%(int)op2; // typecast
operands to int because % supports only int operands
push(res);
break;
case '^':op2=pop();
op1=pop();
res=pow(op1,op2);
push(res);
break;
}// end of switch
} // end of for
res=pop(); // pop the final answer from top of stack
if(top==-1) // Check for empty stack, If true then its
valid postfix expression
printf("\n Result: %f\n ",res); // Display the final
answer
else
{ //otherwise invalid postfix expression
printf("\nINVALID POSTFIX EXPRESSION\n");
top=-1; //reset top to -1
}
PROGRAM 6
Develop a menu driven Program in C for the following operations on Circular QUEUE of
Characters (Array Implementation of Queue with maximum size MAX)
a. Insert an Element on to Circular QUEUE
b. Delete an Element from Circular QUEUE
c. Demonstrate Overflow and Underflow situations on Circular QUEUE
d. Display the status of Circular QUEUE
e. Exit Support the program with appropriate functions for each of the above operations
Observations/Outcome:
1. Better understanding of different types of queues.
2. To understand efficient approaches to implement queue using arrays and linked lists.
Problems on:
1. Creation of Queue using array and then implementation of and operations.
2. Problems on circular queue of array implementation.
ALGORITHM:
Step 1: Start.
Step 2: Initialize queue size to MAX.
Step 3: Insert the elements into circular queue. If queue is full give a message as „queue is
overflow” Step 4: Delete an element from the circular queue. If queue is empty give a
message as „queue is underflow . ‟
Step 5: Display the contents of the queue.
Step 6: Stop.
Source code
#include <stdio.h>
#include <stdlib.h>
#define max 5
int q[max],f=-1,r=-1;
void ins()
{
if(f==(r+1)%max)
printf("\nQueue overflow");
else
{
if(f==-1)
f++;
r=(r+1)%max;
printf("\nEnter element to be inserted:");
scanf("%d",&q[r]);
}
}
void del()
{
if(r==-1)
printf("\nQueue underflow");
else
{
printf("\nElemnt deleted is:%d",q[f]);
if(f==r)
f=r=-1;
else
f=(f+1)%max;
}
}
void disp()
{
if(f==-1)
printf("\nQueue empty");
else
{
int i;
printf("\nQueue elements are:\n");
for(i=f;i!=r;i=(i+1)%max)
printf("%d\t",q[i]);
printf("%d",q[i]);
printf("\nFront is at:%d\nRear is at:%d",q[f],q[r]);
}
}
int main()
{
printf("\nCircular Queue operations");
printf("\n1.Insert");
printf("\n2.Delete");
printf("\n3.Display");
printf("\n4.Exit");
int ch;
do{
printf("\nEnter choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:ins();break;
case 2:del();break;
case 3:disp();break;
case 4:exit(0);
default:printf("\nInvalid choice...!");
}
}while(1);
return 0;
OUTPUT:
SAMPLE OUTPUT 2:
Circular Queue operations
1.insert
2.delete
3.display
4.exit
Enter your choice:1
Enter element to be insert:1000
Enter your choice:1
Enter element to be insert:2000
Enter your choice:1
Enter element to be insert:3000
Enter your choice:3
1000 2000 3000 rear is at 3000 front is at 1000
Enter your choice:2
Deleted element is:1000
Enter your choice:3 2000 3000 rear is at 3000 front is at 2000
Enter your choice:4
Exit
PROGRAM 7
Develop a menu driven Program in C for the following operations on Singly Linked List
(SLL) of Student Data with the fields: USN, Name, Programme, Sem, PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)
e. Exit
ABOUT THE EXPERIMENT: Linked List is a linear data structure and it is very common
data structure which consists of group of nodes in a sequence which is divided in two parts.
Each node consists of its own data and the address of the next node and forms a chain.
Linked Lists are used to create trees and graphs.
• They are a dynamic in nature which allocates the memory when required.
• Insertion and deletion operations can be easily implemented.
• Stacks and queues can be easily executed.
• Linked List reduces the access time.
• Linked lists are used to implement stacks, queues, graphs, etc.
• Linked lists let you insert elements at the beginning and end of the list.
• In Linked Lists we don t need to know the size in advance.
Observations/Outcomes:
1. To get an idea of Linked List and its types.
2. The students will be able to develop Linked List and its type from scratch.
Problems on:
1. Problem on implementation of the various operations on singly Linked List, like
create, display, delete.
2. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)
ALGORITHM:
Step 1: Start.
Step 2: Read the value of N. (N student s information) ‟
Step 3: Create a singly linked list. (SLL)
Step 4: Display the status of SLL.
Step 5: Count the number of nodes.
Step 6: Perform insertion at front of list.
Step 7: Perform deletion at the front of the list.
Step 8: Perform insertion at end of the list.
Step 9: Perform deletion at the end of the list.
Step 10: Demonstrate how singly linked list can be used as stack.
Step 11: Demonstrate how singly linked list can be used as queue.
Step 12: Stop.
SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
struct node
NODE create()
{
NODE snode;
snode = (NODE) malloc(sizeof(struct node));
if (snode == NULL)
{
printf("\nMemory is not available");
exit(1);
}
printf("\nEnter the usn,Name,Branch, sem,PhoneNo of the
student:");
scanf("%s %s %s %d %ld", snode -> usn, snode -> name,
snode -> branch, & snode -> sem, & snode -> phone);
snode -> link = NULL;
count++;
return snode;
}
NODE insertfront()
{
NODE temp;
temp = create();
if (start == NULL)
{
return temp;
}
temp -> link = start;
return temp;
}
NODE deletefront()
{
NODE temp;
if (start == NULL)
{
printf("\nLinked list is empty");
return NULL;
}
if (start -> link == NULL)
{
printf("\nThe Student node with usn:%s is deleted ",
start -> usn);
count--;
free(start);
return NULL;
}
temp = start;
start = start -> link;
printf("\nThe Student node with usn:%s is deleted",
temp -> usn);
count--;
free(temp);
return start;
}
NODE insertend()
{
NODE cur, temp;
temp = create();
if (start == NULL)
{
return temp;
}
cur = start;
while (cur -> link != NULL)
{
cur = cur -> link;
}
cur -> link = temp;
return start;
}
NODE deleteend()
{
NODE cur, prev;
if (start == NULL)
{
printf("\nLinked List is empty");
return NULL;
}
if (start -> link == NULL)
{
printf("\nThe student node with the usn:%s is
deleted",start -> usn);
free(start);
count--;
return NULL;
}
prev = NULL;
cur = start;
while (cur -> link != NULL)
{
prev = cur;
cur = cur -> link;
}
printf("\nThe student node with the usn:%s is deleted",
cur -> usn);
free(cur);
prev -> link = NULL;
count--;
return start;
}
void display()
{
NODE cur;
int num = 1;
if (start == NULL)
{
printf("\nNo Contents to display in SLL \n");
return;
}
printf("\nThe contents of SLL: \n");
cur = start;
while (cur != NULL)
{
printf("\n||%d|| USN:%s| Name:%s| Branch:%s| Sem:%d|
Ph:%ld|", num, cur -> usn, cur -> name, cur ->
branch, cur -> sem, cur -> phone);
cur = cur -> link;
num++;
}
printf("\n No of student nodes is %d \n", count);
}
void stackdemo()
{
int ch;
while (1) {
printf("\n~~~Stack Demo using SLL~~~\n");
printf("\n1:Push operation \n2: Pop operation \n3:
Display \n4:Exit \n");
printf("\nEnter your choice for stack demo:");
scanf("%d", & ch);
switch (ch)
{
case 1:
start = insertfront();
break;
case 2:
start = deletefront();
break;
case 3:
display();
break;
default:
return;
}
}
return;
}
int main()
{
int ch, i, n;
while (1)
{
printf("\n~~~Menu~~~");
printf("\nEnter your choice for SLL operation \n");
printf("\n1:Create SLL of Student Nodes");
printf("\n2:DisplayStatus");
printf("\n3:InsertAtEnd");
printf("\n4:DeleteAtEnd");
printf("\n5:Stack Demo using SLL(Insertion and
Deletion at Front)");
printf("\n6:Exit \n");
printf("\nEnter your choice:");
scanf("%d", & ch);
switch (ch)
{
case 1:
printf("\nEnter the no of students: ");
scanf("%d", & n);
for (i = 1; i <= n; i++)
start = insertfront();
break;
case 2:
display();
break;
case 3:
start = insertend();
break;
case 4:
start = deleteend();
break;
case 5:
stackdemo();
break;
case 6:
exit(0);
default:
printf("\nPlease enter the valid choice");}
}
}
OUTPUT:
~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:1Enter the no of students: 3
Enter the usn,Name,Branch, sem,PhoneNo of the student:
1ME21CS017
Braham
CSE
5
8768586443Enter the usn,Name,Branch, sem,PhoneNo of the
student:
1ME21CS015
Bikash
CSE
5
8734687996Enter the usn,Name,Branch, sem,PhoneNo of the
student:
1ME21AI015
Shoaib
AI&ML
5
6748353877~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:2
The contents of SLL:||1|| USN:1ME21AI015| Name:Shoaib|
Branch:AI&ML| Sem:5| Ph:6748353877|
||2|| USN:1ME21CS015| Name:Bikash| Branch:CSE| Sem:5|
Ph:8734687996|
||3|| USN:1ME21CS017| Name:Braham| Branch:CSE| Sem:5|
Ph:8768586443|
No of student nodes is 3~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:3Enter the usn,Name,Branch,
sem,PhoneNo of the student:
1ME21CS068
Rajan
CSE
5
3426527765~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:2
The contents of SLL:||1|| USN:1ME21AI015| Name:Shoaib|
Branch:AI&ML| Sem:5| Ph:6748353877|
||2|| USN:1ME21CS015| Name:Bikash| Branch:CSE| Sem:5|
Ph:8734687996|
||3|| USN:1ME21CS017| Name:Braham| Branch:CSE| Sem:5|
Ph:8768586443|
||4|| USN:1ME21CS068| Name:Rajan| Branch:CSE| Sem:5|
Ph:3426527765|
No of student nodes is 4~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:4
The student node with the usn:1ME21CS068 is deleted~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:2
The contents of SLL:||1|| USN:1ME21AI015| Name:Shoaib|
Branch:AI&ML| Sem:5| Ph:6748353877|
||2|| USN:1ME21CS015| Name:Bikash| Branch:CSE| Sem:5|
Ph:8734687996|
||3|| USN:1ME21CS017| Name:Braham| Branch:CSE| Sem:5|
Ph:8768586443|
No of student nodes is 3~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:4
The student node with the usn:1ME21CS017 is deleted~~~Menu~~~
Enter your choice for SLL operation1:Create SLL of Student
Nodes
2:DisplayStatus
3:InsertAtEnd
4:DeleteAtEnd
5:Stack Demo using SLL(Insertion and Deletion at Front)
6:ExitEnter your choice:5
~~~Stack Demo using SLL~~~1:Push operation
2: Pop operation
3: Display
4:ExitEnter your choice for stack demo:1Enter the
usn,Name,Branch, sem,PhoneNo of the student:
1ME21CS005
Aman
CSE
5
6587594335~~~Stack Demo using SLL~~~1:Push operation
2: Pop operation
3: Display
4:ExitEnter your choice for stack demo:3
The contents of SLL:||1|| USN:1ME21CS005| Name:Aman|
Branch:CSE| Sem:5| Ph:6587594335|
||2|| USN:1ME21AI015| Name:Shoaib| Branch:AI&ML| Sem:5|
Ph:6748353877|
||3|| USN:1ME21CS015| Name:Bikash| Branch:CSE| Sem:5|
Ph:8734687996|
No of student nodes is 3~~~Stack Demo using SLL~~~1: Push
operation
2: Pop operation
3: Display
4: ExitEnter your choice for stack demo:1Enter the
usn,Name,Branch, sem,PhoneNo of the student:
1ME21CS092
Shubham
CSE
5
9869754354~~~Stack Demo using SLL~~~
1:Push operation
2: Pop operation
3: Display
4:ExitEnter your choice for stack demo:3
The contents of SLL:||1|| USN:1ME21CS092| Name:Shubham|
Branch:CSE| Sem:5| Ph:9869754354|
||2|| USN:1ME21CS005| Name:Aman| Branch:CSE| Sem:5|
Ph:6587594335|
||3|| USN:1ME21AI015| Name:Shoaib| Branch:AI&ML| Sem:5|
Ph:6748353877|
||4|| USN:1ME21CS015| Name:Bikash| Branch:CSE| Sem:5|
Ph:8734687996|
No of student nodes is 4~~~Stack Demo using SLL~~~1:Push
operation
2: Pop operation
3: Display
PROGRAM 8
Develop a menu driven Program in C for the following operations on Doubly Linked
List (DLL) of Employee Data with the fields: SSN, Name, Dept, Designation, Sal, PhNo
a. Create a DLL of N Employees Data by using end insertion.
b. Display the status of DLL and count the number of nodes in it
c. Perform Insertion and Deletion at End of DLL
d. Perform Insertion and Deletion at Front of DLL
e. Demonstrate how this DLL can be used as Double Ended Queue.
f. Exit
Problems on:
1. Problem on implementation of the various operations on Linked List, like create, display,
delete.
2. Program to create doubly linked list, and Count no of nodes.
3. Inserting, deleting elements in linked list at various position.
Observations/Outcomes:
1. To get an idea of Linked List and its types.
2. The students will be able to develop Linked List and its type from scratch
ALGORITHM:
Step 1: Start.
Step 2: Read the value of N. (N student s information) ‟
Step 3: Create a doubly linked list. (DLL)
Step 4: Display the status of DLL.
Step 5: Count the number of nodes.
Step 6: Perform insertion at front of list.
Step 7: Perform deletion at the front of the list.
Step 8: Perform insertion at end of the list.
Step 9: Perform deletion at the end of the list.
Step 10: Demonstrate how doubly linked list can be used as double ended queue.
Step 11: Stop.
SOURCE CODE
#include<stdio.h>
#include<stdlib.h>
struct node
{
char ssn[25], name[25], dept[10], designation[25];
int sal;
long int phone;
struct node * llink;
struct node * rlink;
};
typedef struct node * NODE;
NODE first = NULL;
int count = 0;NODE
create()
{
NODE enode;
enode = (NODE) malloc(sizeof(struct node));
if (enode == NULL)
{
printf("\nRunning out of memory");
exit(0);
}
printf("\nEnter the ssn, Name, Department,
Designation, Salary, PhoneNo of the
employee:\n");
scanf("%s %s %s %s %d %ld", enode -> ssn, enode -> name,
enode -> dept, enode -> designation, & enode ->
sal, & enode -> phone);
enode -> llink = NULL;
enode -> rlink = NULL;
count++;
return enode;
}
NODE insertfront()
{
NODE temp;
temp = create();
if (first == NULL)
{
return temp;
}
temp -> rlink = first;
first -> llink = temp;
return temp;
}
void display()
{
NODE cur;
int nodeno = 1;
cur = first;
if (cur == NULL)
printf("\nNo Contents to display in DLL");
while (cur != NULL)
{
printf("\nENode:%d||SSN:%s|Name:%s|Department:%s|
Designation:%s|Salary:%d|Phone no:%ld", nodeno,
cur -> ssn, cur -> name, cur -> dept, cur ->
designation, cur -> sal, cur -> phone);
cur = cur -> rlink;
nodeno++;
}
printf("\nNo of employee nodes is %d", count);
}
NODE deletefront()
{
NODE temp;
if (first == NULL)
{
printf("\nDoubly Linked List is empty");
return NULL;
}
if (first -> rlink == NULL)
{
printf("\nThe employee node with the ssn:%s
is deleted", first -> ssn);
free(first);
count--;
return NULL;
}
temp = first;
first = first -> rlink;
temp -> rlink = NULL;
first -> llink = NULL;
printf("\nThe employee node with the ssn:%s
is deleted", temp -> ssn);
free(temp);
count--;
return first;
}
NODE insertend()
{
NODE cur, temp;
temp = create();
if (first == NULL)
{
return temp;
}
cur = first;
while (cur -> rlink != NULL)
{
cur = cur -> rlink;
}
cur -> rlink = temp;
temp -> llink = cur;
return first;
}
NODE deleteend()
{
NODE prev, cur;
if (first == NULL)
{
printf("\nDoubly Linked List is empty");
return NULL;
}
if (first -> rlink == NULL)
{
printf("\nThe employee node with the ssn:%s
is deleted", first -> ssn);
free(first);
count--;
return NULL;
}
prev = NULL;
cur = first;
while (cur -> rlink != NULL)
{
prev = cur;
cur = cur -> rlink;
}
cur -> llink = NULL;
printf("\nThe employee node with the ssn:%s
is deleted", cur -> ssn);
free(cur);
prev -> rlink = NULL;
count--;
return first;
}
void deqdemo()
{
int ch;
while (1)
{
printf("\nDemo Double Ended Queue Operation");
printf("\n1:InsertQueueFront\n 2: DeleteQueueFront\n
3:InsertQueueRear\n 4:DeleteQueueRear\n
5:DisplayStatus\n 6: Exit \n");
scanf("%d", & ch);
switch (ch)
{
case 1:
first = insertfront();
break;
case 2:
first = deletefront();
break;
case 3:
first = insertend();
break;
case 4:
first = deleteend();
break;
case 5:
display();
break;
default:
return;
}
}
}
void main()
{
int ch, i, n;
while (1)
{
printf("\n\n~~~Menu~~~");
printf("\n1:Create DLL of Employee Nodes");
printf("\n2:DisplayStatus");
printf("\n3:InsertAtEnd");
printf("\n4:DeleteAtEnd");
printf("\n5:InsertAtFront");
printf("\n6:DeleteAtFront");
printf("\n7:Double Ended Queue Demo using DLL");
printf("\n8:Exit \n");
printf("\nPlease enter your choice: ");
scanf("%d", & ch);
switch (ch)
{
case 1:
printf("\nEnter the no of Employees: ");
scanf("%d", & n);
for (i = 1; i <= n; i++)
first = insertend();
break;
case 2:
display();
break;
case 3:
first = insertend();
break;
case 4:
first = deleteend();
break;
case 5:
first = insertfront();
break;
case 6:
first = deletefront();
break;
case 7:
deqdemo();
break;
case 8:
exit(0);
default:
printf("\nPlease Enter the valid choice");
}
}
}
PROGRAM 9
Develop a Program in C for the following operationson Singly Circular Linked List
(SCLL) with header nodes
a. Represent and Evaluate a Polynomial P(x,y,z) = 6x 2 y 2 z-4yz 5 +3x 3 yz+2xy 5 z-2xyz 3
b. Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the
result in POLYSUM(x,y,z)
Support the program with appropriate functions for each of the above operations
SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct
node1
{
int coef, po_x,po_y,po_z;
struct node1 *next;
};
typedef struct node1* node;
q= head;
while(q-
>next!=head
) q=q->next;
q->next=p;
p->next=head;
return head;
}
void display(node head)
{
if(head->next==head)
{
printf("Polynomial is enmpty");
return;
}
node cur;
cur=head-
>next; do
{
printf("%dx^ %dy^%dz^%d",cur->coef,cur-
>po_x,cur->po_y,cur->po_z); cur=cur-
>next;
if(cur!=head)
{
printf(" + ");
}
}while(cur!=h
ead);
printf("\n");
}
int eval(node head, int x, int y , int z)
{
int ans=0, term;
if(head->next==head)
{
return ans;
}
return ans;
}
do
{
cur1=res-
>next;
bool
flag1=fals
e; do
{
if(match(cur1,cur2))
{
cur1-
>coef+=cur2-
>coef;
flag1=true;
break;
}
cur1=cur1->next;
}while(cur1!=res);
if(!flag1)
res=insert(res,cur2->coef,cur2-
>po_x,cur2->po_y,cur2->po_z); cur2=cur2-
>next;
}while(cur2!=p2);
return res;
}
int main()
{
node
p1=(node)malloc(sizeof(
struct node1)); p1-
>next=p1;
node p2=
(node)malloc(sizeof(stru
ct node1)); p2->next=p2;
p1=insert(p1,+6,2,2,1);
p1=insert(p1,-4,0,1,5);
p1=insert(p1,+3,3,1,1);
p1=insert(p1,+2,1,5,1);
p1=insert(p1,-2,1,1,3);
printf("p1(
X,Y,Z)=
\n");
display(p1)
;
p2=insert(p2,+1,1,1,1);
p2=insert(p2,+4,3,1,1);
printf("p2
(x,y,z)=
\n");
display(p2)
;
res=add(p1,p2,res);
printf("Addition of two
polynomials : res(x,y,z)= \n");
display(res);
int x,y,z;
x=1;
y=2;
z=3;
int ires;
ires=eval
(res, x,
y ,z);
printf("\n res of polysum(%d,%d,%d): %d) \n ", x,y,z, ires);
return 0;
}
PROGRAM 10
Develop a menu driven Program in C for the following operations on Binary Search
Tree (BST) of Integers .
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
b. Traverse the BST in Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
ALGORITHM:
Step 1: Start.
Step 2: Create a Binary Search Tree for N elements.
Step 3: Traverse the tree in inorder.
Step 4: Traverse the tree in preorder
Step 5: Traverse the tree in postorder.
Step 6: Search the given key element in the BST.
Step 7: Delete an element from BST.
Step 8: Stop
SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
struct BST
{
int data;
struct BST * lchild;
struct BST * rchild;
};
typedef struct BST * NODE;
NODE create()
{
NODE temp;
temp = (NODE) malloc(sizeof(struct BST));
printf("\nEnter The value: ");
scanf("%d", & temp -> data);temp -> lchild = NULL;
temp -> rchild = NULL;
return temp;
}
void insert(NODE root, NODE newnode);
void inorder(NODE root);
void preorder(NODE root);
void postorder(NODE root);
void search(NODE root);
{
printf("\nBST is empty.");
return;
}
printf("\nEnter Element to be searched: ");
scanf("%d", & key);
cur = root;
while (cur != NULL)
{
if (cur -> data == key)
{
printf("\nKey element is present in BST");
return;
}
if (key < cur -> data)
cur = cur -> lchild;
else
cur = cur -> rchild;
}
printf("\nKey element is not found in the BST");
}
void main()
{
int ch, key, val, i, n;
NODE root = NULL, newnode;
while (1)
{
printf("\n~~~~BST MENU~~~~");
printf("\n1.Create a BST");
printf("\n2.Search");
printf("\n3.BST Traversals: ");
printf("\n4.Exit");
printf("\nEnter your choice: ");
scanf("%d", & ch);
switch (ch)
{
case 1:
printf("\nEnter the number of elements: ");
scanf("%d", & n);
for (i = 1; i <= n; i++)
{
newnode = create();
if (root == NULL)
root = newnode;
else
insert(root, newnode);
}
break;
case 2:
if (root == NULL)
printf("\nTree Is Not Created");
else
{
printf("\nThe Preorder display : ");
preorder(root);
printf("\nThe Inorder display : ");
inorder(root);
printf("\nThe Postorder display : ");
postorder(root);
}
break;
case 3:
search(root);
break;
case 4:
exit(0);
}
}
}
output:
~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 1Enter the number of elements: 12
Enter The value: 6
Enter The value: 9
Enter The value: 5
Enter The value: 2
Enter The value: 8
Enter The value: 15
Enter The value: 24
Enter The value: 14
Enter The value: 7
Enter The value: 8
Enter The value: 5
Enter The value: 2~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 3The Preorder display: 6
5 2 9 8 7 15
14 24
The Inorder display: 2 5 6
7 8 9 14 15 24
The Postorder display: 2 5 7
8 14 24 15 9 6~~~~BST
MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 2Enter Element to be searched: 66
Key element is not found in the BST~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 2Enter Element to be searched: 14
Key element is present in BST~~~~BST MENU~~~~
1.Create a BST
2.Search
3.BST Traversals:
4.Exit
Enter your choice: 4
PROGRAM 11
Develop a Program in C for the following operations on Graph(G) of Cities
a. Create a Graph of N cities using Adjacency Matrix.
b. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS
method
ALGORITHM:
Step 1: Start.
Step 2: Input the value of N nodes of the graph
Step 3: Create a graph of N nodes using adjacency matrix representation.
Step 4: Print the nodes reachable from the starting node using BFS.
Step 5: Check whether graph is connected or not using DFS.
Step 6: Stop
SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
int a[50][50], n, visited[50];
int q[20], front = -1, rear = -1;
int s[20], top = -1, count = 0;
void bfs(int v)
{
int i, cur;
visited[v] = 1;
q[++rear] = v;
while (front != rear)
{
cur = q[++front];
for (i = 1; i <= n; i++)
{
if ((a[cur][i] == 1) && (visited[i] == 0))
{
q[++rear] = i;
visited[i] = 1;
printf("%d ", i);
}
}
}
}
void dfs(int v)
{
int i;
visited[v] = 1;
s[++top] = v;
for (i = 1; i <= n; i++)
{
if (a[v][i] == 1 && visited[i] == 0)
{
printf("%d ", i);
dfs(i);
}
}
}
int main()
{
int ch, start, i, j;
printf("\nEnter the number of vertices in graph:");
scanf("%d", & n);
printf("\nEnter the adjacency matrix:\n");
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
scanf("%d", & a[i][j]);
}
for (i = 1; i <= n; i++)
visited[i] = 0;
printf("\nEnter the starting vertex: ");
scanf("%d", & start);printf("\n==>1. BFS:
Print all nodes reachable from a given
starting node");
printf("\n==>2. DFS: Print all nodes reachable from a
given starting node");
printf("\n==>3:Exit");
printf("\nEnter your choice: ");
scanf("%d", & ch);
switch (ch)
{
case 1:
printf("\nNodes reachable from
starting vertex %d are: ", start);
bfs(start);
for (i = 1; i <= n; i++)
{
if (visited[i] == 0)
printf("\nThe vertex that is not
reachable is %d", i);
}
break;
case 2:
printf("\nNodes reachable from
starting vertex %d are:\n", start);
dfs(start);
break;
case 3:
exit(0);
default:
printf("\nPlease enter valid choice:");
}
}
Output:
*************************case-
1*************************Enter the number of
vertices in graph:4
Enter the adjacency matrix:
0 1 0 1
0 0 1 0
0 0 0 1
0 0 0 0
Enter the starting vertex: 1
==>1. BFS: Print all nodes reachable from a given
starting node
==>2. DFS: Print all nodes reachable from a given
starting node
==>3:Exit
Enter your choice: 1
Nodes reachable from starting vertex 1 are: 2 4
3*************************case-
2*************************Enter the number of
vertices in graph:4
Enter the adjacency matrix:
0 1 0 1
0 0 1 0
0 0 0 1
0 0 0 0
Enter the starting vertex: 2
==>1. BFS: Print all nodes reachable from a given
starting node
==>2. DFS: Print all nodes reachable from a given
starting node
==>3:Exit
Enter your choice: 1
Nodes reachable from starting vertex 2 are: 3 4
The vertex that is not reachable is
1*************************case-
3*************************Enter the number of
vertices in graph:4
Enter the adjacency matrix:
0 1 0 1
0 0 1 0
0 0 0 1
0 0 0 0
Enter the starting vertex: 1
==>1. BFS: Print all nodes reachable from a given
starting node
==>2. DFS: Print all nodes reachable from a given
starting node
==>3:Exit
Enter your choice: 2
Nodes reachable from starting vertex 1 are: 2 3
4*************************case-
4*************************Enter the number of
vertices in graph:4
Enter the adjacency matrix:
0 1 0 1
0 0 1 0
0 0 0 1
0 0 0 0
Enter the starting vertex: 2
==>1. BFS: Print all nodes reachable from a given
starting node
==>2. DFS: Print all nodes reachable from a given
starting node
==>3:Exit
Enter your choice: 2
Nodes reachable from starting vertex 2 are: 3 4
PROGRAM 12
Given a File of N employee records with a set K of Keys (4-digit) which uniquely
determine the records in file F. Assume that file F is maintained in memory by a Hash
Table (HT) of m memory locations with L as the set of memory addresses (2-digit) of
locations in HT. Let the keys in K and addresses in L are Integers.
Develop a Program in C that uses Hash function H: K →L as H(K)=K mod m
(remainder method), and implement hashing technique to map a given key K to the
address space L.
Resolve the collision (if any) using linear probing.
ALGORITHM:
Step 1: Start.
Step 2: Given a File of N employee records with a set K of Keys (4-digit) which uniquely
determine the records in file F.
Step 3: Assume that file F is maintained in memory by a Hash Table(HT) of m memory
locations with L as the set of memory addresses (2-digit) of locations in HT.
Step 4: Let the keys in K and addresses in L are Integers
Step 5: Hash function H: K ®L as H(K)=K mod m (remainder method)
Step 6: Hashing as to map a given key K to the address space L, Resolve the collision (if any)
is using linear probing.
Step 7: Stop.
SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
int key[20], n, m;
int * ht, index;
int count = 0;
void insert(int key)
{
index = key % m;
while (ht[index] != -1)
{
index = (index + 1) % m;
}
ht[index] = key;
count++;
}
void display()
{
int i;
if (count == 0)
{
printf("\nHash Table is empty");
return;
}
printf("\nHash Table contents are:\n ");
for (i = 0; i < m; i++)
printf("\n T[%d] --> %d ", i, ht[i]);
}
void main()
{
int i;
printf("\nEnter the number of employee records (N) :");
scanf("%d", & n);
printf("\nEnter the two
digit memory locations (m) for hash table:");
scanf("%d", & m);ht = (int * ) malloc(m * sizeof(int));
for (i = 0; i < m; i++)
ht[i] = -1;
printf("\nEnter the four digit key values (K) for N
Employee Records:\n ");
for (i = 0; i < n; i++)
scanf("%d", & key[i]);for (i = 0; i < n; i++) {
if (count == m)
{
printf("\n~~~Hash table is full.
Cannot insert the record %d key~~~", i + 1);
break;
}
insert(key[i]);
}//Displaying Keys inserted into hash table
display();
}
Output:
Enter the number of employee records (N) :10
Enter the two digit memory locations (m) for hash table:15
Enter the four digit key values (K) for N Employee Records:
4020
4560
9908
6785
0423
7890
6547
3342
9043
6754
Hash Table contents are:
T[0] --> 4020
T[1] --> 4560
T[2] --> 7890
T[3] --> 423
T[4] --> 6754
T[5] --> 6785
T[6] --> -1
T[7] --> 6547
T[8] --> 9908
T[9] --> -1
T[10] --> -1
T[11] --> -1
T[12] --> 3342
T[13] --> 9043
T[14] --> -1