Data Structure Lab Manual 2021-22
Data Structure Lab Manual 2021-22
LABORATORY MANUAL
Objectives
To provide quality education and groom top-notch professionals, entrepreneurs and
leaders for different fields of engineering, technology and management.
To open a Training-R & D-Design-Consultancy cell in each department, gradually
introduce doctoral and postdoctoral programs, encourage basic & applied research in
areas of social relevance, and develop the institute as a center ofexcellence.
To develop academic, professional and financial alliances with the industry as well as
the academia at national and transnational levels.
To develop academic, professional and financial alliances with the industry as well as
the academia at national and transnational levels.
To cultivate strong community relationships and involve the students and the staff in
local communityservice.
To constantly enhance the value of the educational inputs with the participation of
students, faculty, parents and industry.
Vision
Development ofacademically excellent, culturally vibrant, socially responsible and
globally competent human resources.
Mission
To keep pace with advancements inknowledge and makethe students competitive and
capable at the global level.
To create an environment for the students to acquire the right physical, intellectual,
emotional and moral foundations and shine as torch bearers oftomorrow’s society.
To strive to attain ever-higher benchmarks of educational excellence.
Department of Computer Science & Engineering
Motivate students to put their thoughts and ideas adoptable by industry or to pursue
higher studies leading to research.
PO2. 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.
PO5. 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.
PO6. 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.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO11. 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.
PO12. 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.
PSO1: Ability to apply skills in the field of algorithms, database design, web design, cloud
computing and data analytics.
PSO2: Apply knowledge in the field of computer networks for building network and internet
based applications.
Program Educational Objectives (PEOs):
1. Empower students with a strong basis in the mathematical, scientific and engineering
fundamentals to solve computational problems and to prepare them for employment,
higher learning and R&D.
4. Design, Develop and Implement 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.
5. Design, Develop and Implement 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
6. Design, Develop and Implement 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 CircularQUEUE
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
7. Design, Develop and Implement a menu driven Program in C for the following operations on
Singly Linked List (SLL) of Student Data with the fields: USN, Name, Branch, Sem, PhNo
a. Create a SLL of N Students Data by using frontinsertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at EndofSLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration ofstack)
e. Exit
8. Design, Develop and Implement 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 endinsertion.
b. Display the status of DLL and count the number of nodes init
c. Perform Insertion and Deletion at End ofDLL
d. Perform Insertion and Deletion at Front ofDLL
e. Demonstrate how this DLL can be used as Double EndedQueue.
f. Exit
10. Design, Develop and Implement 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 IN order, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
11. Design, Develop and Implement a Program in C for the following operations on Graph(G)
of Cities
a. Create a Graph of N cities using AdjacencyMatrix.
b. Print all the nodes reachable from a givenstarting node in a digraph usingDFS/BFS
method
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. Design and 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.
Laboratory Outcomes: The student should be able to:
Analyze and Compare various linear and non-linear data structures
Code, debug and demonstrate the working nature of different types of data structures andtheir
applications
Implement, analyze and evaluate the searching and sortingalgorithms
Choose the appropriate data structure for solving real world problems
Conduct of Practical Examination:
Experiment distribution
o For laboratories having only one part: Students are allowed to pick one experiment from the
lot with equal opportunity.
o For laboratories having PART A and PART B: Students are allowed to pick one
experiment from PART A and one experiment from PART B, with equal opportunity.
Change of experiment is allowed only once and marks allotted for procedure to be made zero of the
changed part only.
Marks Distribution (Courseed to change in accoradance with university regulations)
c) For laboratories having only one part – Procedure + Execution + Viva-Voce: 15+70+15=
100 Marks
d) For laboratories having PART A and PART B
i. Part A – Procedure + Execution + Viva = 6 + 28 + 6 = 40 Marks
Part B – Procedure + Execution + Viva = 9 + 42 + 9 = 60Marks
CONTENTS
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.
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 non linear 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.
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.1 2 3 4 5
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.
APPLICATION OF QUEUE
Queue, as the name suggests is used whenever we need to have any group of objects in an
order in which the first one coming in, also gets out first while the others wait for their turn,
like in the following scenarios :
Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
In real life, Call Center phone systems will use Queues, to hold people calling them in an
order, until a service representative is free.
Handling of interrupts in real-time systems. The interrupts are handled in the same order as
they arrive, First come first served.
LINKED LIST
Disadvantages of static/sequential allocation technique:
If an item has to be deleted then all the following items will have to be moved by one
allocation. Wastage of time.
Inefficient memory utilization.
If no consecutive memory (free) is available, execution is not possible.
NODE:
Each node consists of two fields. Information (info) field and next address (next) field. The
info field consists of actual information/data/item that has to be stored in a list. The second
field next/link contains the address of the next node. Since next field contains the address,
It is of type pointer. Here the nodes in the list are logically adjacent to each other. Nodes that
are physically adjacent need not be logically adjacent in the list.
The entire linked list is accessed from an external pointer FIRST that points to (contains the
address of) the first node in the list. (By an “external” pointer, we mean, one that is not
included within a node. Rather its value can be accessed directly by referencing a variable).
As each node is having only one link/next, the list is called single linked list and all the
nodes are linked in one direction. Each node can be accessed by the pointer pointing (holding
the address) to that node, Say P is pointer to a particular node, then the information field of that
node can be accessed using info(P) and the next field can be accessed using next(P).
The arrows coming out of the next field in the fig. indicates that the address of the
succeeding node is stored in that field. The link field of last node contains a special value
known as NULL which is shown using a diagonal line pictorially. This NULL pointer is used
to signal the end of a list.
The basic operations of linked lists are Insertion, Deletion and Display. A list is a
dynamic data structure. The number of nodes on a list may vary dramatically as elements are
inserted and deleted(removed).
The dynamic nature of list may be contrasted with the static nature of an array, whose
size remains constant. When an item has to inserted, we will have to create a node, which has
to be got from the available free memory of the computer system, So we shall use a mechanism
to find an unused node which makes it available to us. For this purpose we shall use the
getnode operation (getnode() function).
The C language provides the built-in functions like malloc(), calloc(), realloc() and
free(), which are stored in alloc.h or stdlib.h header files. To dynamically allocate and release
the memory locations from/to the computer system.
TREES:
Definition:
A data structure which is accessed beginning at the root node. Each node is either a
leaf or an internal node. An internal node has one or more child nodes and is called the parent
of its child nodes. All children of the same node are siblings. Contrary to a physical tree, the
root is usually depicted at the top of the structure, and the leaves are depicted at the bottom. A
tree can also be defined as a connected, acyclic di-graph.
Tree is a non-linear data structure which organizes data in hierarchical structure and this is a
recursive definition.
A tree data structure can also be defined as follows...
Tree data structure is a collection of data (Node) which is organized in hierarchical structure
and this is a recursive definition
Binary tree: A tree with utmost two children for each node.
Complete Binary Tree: A binary tree in which every level, except possibly the deepest, is
completely filled. At depth n, the height of the tree, all nodes must be as far left as possible.
Binary search tree: A binary tree where every node’s left subtree has keys less than the node's
key, and every right subtree has keys greater than the node's key.
Tree traversal is a technique for processing the nodes of a tree in some order.The
different tree traversal techniques are Pre-order, In-order and Post-order traversal.In Pre-order
traversal, the tree node is visited first and the left subtree is traversed recursively and later right
sub-tree is traversed recursively.
PROGRAM 1
Design, Develop and Implement a menu driven Program in C for the
following Array operations
a. Creating an Array of N Integer Elements
b. Display of Array Elements with Suitable Headings
c. Inserting an Element (ELEM) at a given valid Position (POS)
d. Deleting an Element at a given valid Position(POS)
e. Exit.
Support the program with functions for each of the above operations
Program objective:
Understand the working of array datastructures.
Understand the use of functions to implement each arrayoperation.
Understand what is menu driven program and how to implement it.
Algorithm:
Step 1: Start.
Step 2: Read number of elements.(n)
Step 3: Read Array of N integerelements
Step 4: Display array contents and checking array empty condition
Step 5: Read valid position, to insert element into that position
Step 6: Delete an element at given valid position from an array.
Step 7: Stop
THEORY:
Array is a collection of elements of the same type. In this program we need to use functions for
various operations
Create (): Create an array for the size given by the user
Display (): Display the elements of the array
Insert (): Insert an element at the position given by the user
Delete (): Delete an element from the position specified by the user
Exit (): Terminate
Arrays are the kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an arrayas a collection of variables of the sametype.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows –
type array Name [ arraySize ];
This is called a single-dimensional array. The array Size must be an integer constant
greater than zero and type can be any valid C data type.
For example, to declare a 10-element array called balance of type double, use this statement –
double balance [10];
You can initialize an array in C either one by one or using a single statement as follows –
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
#include<stdio.h>
#include<stdlib.h>
int a[20],n,i,por,val,choice;
void create();
void display();
void insert();
void delete();
void main()
{
while(1)
{
printf("....MENU...|n");
printf("1.create\n 2.display\n 3.insert\n 4.delete\n 5.exit\n");
printf("enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:create();
break;
case 2:display();
break;
case 3:insert();
break;
case 4:delete();
break;
case 5:exit(0);
break;
default:printf("invalid choice\n");
break;
}
}
}
void create()
{
printf("enter the number of elements\n");
scanf("%d",&n);
DEPT OF CSE, ATMECE, MYSURU Page 8
DATA STRUCTURES LABORATORY 18CSL38
Output
Program outcome:
Implement the menu driven C program using switchstatement.
Implement an array of any size and all the possible operationsonarray.
Identify the different applications where arrays can be used.
Familiarized with the usage of functions in program.
Viva Questions:
What is a array?
What is two dimensional array?
How to access elements of array?
Can you change size of array once created?\
What is two dimensional array?
How An array elements are always stored in memory locations.?
PROGRAM 2
Design, develop and implement 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
Program objective:
Understand the implementation of string function’s using arrays.
Understand pattern matching algorithm and theimplementationtechniqueof
the same without using built-in functions.
Understand the pattern replacement methodology.
Algorithm:
Step 1: Start.
Step 2: Read main string STR, pattern string PAT and replace string REP.
Step 3: compare pattern string in main string,
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.
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."
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:
PROGRAM:
#include<stdio.h>
void read();
void match();
char STR[100],PAT[100],REP[100],ANS[100];
int c,i,j,k,m,flag=0;
main()
{
read();
match();
}
void read()
{
printf("enter the main string STR:");
gets(STR);
printf("enter pattern string PAT:");
gets(PAT);
printf("enter replace string REP:");
gets(REP);
}
void match()
{
c=i=j=k=m=0;
while(STR[c]!='\0')
{
if(STR[m]==PAT[i])
{
i++;m++;
flag=1;
if(PAT[i]=='\0')
{
for(k=0;REP[k]!='\0';k++,j++)
ANS[j]=REP[k];
i=0;
DEPT OF CSE, ATMECE, Mysuru Page 16
DATA STRUCTURES LABORATORY 18CSL38
c=m;
}
}
else
{
ANS[j]=STR[c];
j++;c++;
m=c;
i=0;
}
}
if(flag==0)
printf("pattern not found");
else
{
ANS[j]='\0';
printf("resultant string is %s",ANS);
}
}
Output 1
Enter the MAIN string:
atme college of engg
Enter a PATTERN string:
engg
Enter a REPLACE string:
engineering
The RESULTANT string is: atme college of engineering
Output 2
Enter the MAIN string:
atme college of engg
Enter a PATTERN string:
for
Enter a REPLACE string:
if
Pattern doesn't found!!!
Output 3
Enter the MAIN string:
This is Data Structure lab
Enter a PATTERN string:
Data Structure
Enter a REPLACE string:
Data structure with C
The RESULTANT string is: This is Data structure with C lab
Program outcomes:
Implement string matchingand string replacement algorithmwithout using
built-in library functions.
Apply the knowledge of array usage to implement string functions.
Identify different applications of string matching andstringreplacement.
Viva Questions:
What is a string?
How strings are represented in C language? What does strlen do in C?
Is there a string data type in C? What is the use of char in Cprogramming?
PROGRAM 3
Design, Develop and Implement 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 ontoStack
b Pop an Element fromStack
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.
Program objective:
Understand the concept of palindrome.
Understand the stack data structures.
Understand the different functions onstacks i.e., push, pop and implement the
same.
Understand stack overflow and underflow.
Algorithm:
PUSH (item)
Step 1: Read an element to be pushed on to stack item
Step 2: check overflow condition of stack before inserting element into
stack Top=max-1
Step 3: update the top pointer and insert an element into stack
Top=top+1
S[top] <-item
POP (item)
Step1: check underflow condition of stack before deleting element from stack
top=-1
Step2: Display deleted element pointed by top
Deleted element<- s[top]
Step3: Decrement top pointer by 1
top<-top-1
Palindrome
Step 1: Two pointers are required , one is pointed to top of stack
another is bottom of stack
Step 2: compare top and bottom elements of stack if it is equal update top and
bottom pointer by1
Step 3: if all elements are equal, then stack content is palindrome
THEORY
It is called as last in, first out. The element inserted first is the last one to be deleted. It
is used for various applications like infix to postfix expression, postfix evaluation and for
maintaining stack frames for function calling
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.
Fig4-Example of Stack
A stack can be implemented by means of Array, Structure, Pointer and Linked-List. Stack
can either be a fixed size one or it may have a sense of dynamic resizing.
Here, we are going to implement stack using arrays which makes it a fixed size stack
implementation.
#include<stdio.h>
#include<stdlib.h>
#define MAX 4
int stack[MAX],top=-1,item;
void push();
void pop();
void palindrome();
void display();
void main()
{
int choice;
while(1)
{
Printf(“------- STACK OPERATIONS ------ \n“);
printf("1.push\n 2.pop\n 3.palindrome\n 4.display\n 5.exit\n");
printf("enter choice");
scanf("%d",&choice);
switch(choice)
{
case 1:push();
break;
case 2:pop();
break;
case 3:palindrome();
break;
case 4:display();
break;
case 5:exit(0);
break;
default:printf("invalid choice\n");
break;
}
}
}
void push()
{
if(top==MAX-1)
printf("stack overflow");
else
{
printf("enter the item to be pushed\n");
scanf("%d",&item);
top=top+1;
stack[top]=item;
}
}
void pop()
{
if(top==-1)
printf("stack underflow");
else
{
item=stack[top];
top=top-1;
printf("deleted item is %d",item);
}
}
void display()
{
int i;
if(top==-1)
printf("stack is empty");
else
{
for(i=top;i>=0;i--)
printf("%d\t",stack[i]);
}
}
Output
Viva Questions:
What is Stack and where it can be used?
What is the difference between PUSH and POP?
Differentiate STACK from ARRAY.
What is the difference between a stack and a Queue?
PROGRAM 4
Design, develop and implement 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.
Program objective:
Understand different notations to represent regular expression.
Understand infix to postfix conversion.
Understand the precedence of operators.
Algorithm:
Step 1: Read the infix expression as a string.
Step 2: Scan the expression character by character till the end. Repeat the
following operations
1. If it is an operand add it to the postfixexpression.
2. If it is a left parenthesis push it onto the stack.
3. If it is a right parentheses pop out elements from the stack and assign it to
the postfix string. Pop out the left parentheses but don’t assign topostfix.
Step 3: If it is an operator compare its precedence with that of the element at the
top of stack.
1. If it is greater push it onto the stack.
2. Else pop and assignelements in the stack to the postfixexpression until
you find one such element.
Step 4: If you have reached the end of the expression, pop out any leftover
elements in the stack till it becomes empty.
Step 5: Append a null terminator at the end display the result
THEORY
Infix: Operators are written in-between their operands. Ex: X + Y
Prefix: Operators are written before their operands. Ex: +X Y postfix: Operators are written
after their operands. Ex: XY+
Step 5. Result
+*+A^BCD^E5
PROGRAM:
#include<stdio.h>
#include<ctype.h>
#define SIZE 50
char s[SIZE];
int top=-1;
void push(char elem)
{
s[++top]=elem;
}
char pop()
{
return s[top--];
}
int pr(char elem)
{
switch(elem)
{
case '#':return 0;
case '(':return 1;
case '+':
case '-':return 2;
case '*':
case '/':
case '%':return 3;
case '^':return 4;
}
}
void main()
{
char infix[50],postfix[50],ch,elem;
int i=0,k=0;
printf("enter the infix expression\n");
gets(infix);
push('#');
while((ch=infix[i++])!='\0')
DEPT OF CSE, ATMECE, MYSURU Page 31
DATA STRUCTURES LABORATORY 18CSL38
{
if(ch=='(')
push(ch);
else if(isalnum(ch))
postfix[k++]=ch;
else if(ch==')')
{
while(s[top]!='(')
postfix[k++]=pop();
elem=pop();
}
else
{
while(pr(s[top])>=pr(ch))
postfix[k++]=pop();
push(ch);
}
}
while(s[top]!='#')
postfix[k++]=pop();
postfix[k]='\0';
printf("infix expression is %s\n postfix expression is %s\n",infix,postfix);
}
Output1
enter the Infix Expression
((a+b)*c)
Given Infix Expn is: ((a+b)*c)
The Postfix Expn is: ab+c*
Output 2
enter the Infix Expression
(a+ (b-c)*d)
Given Infix Expn is: (a+ (b-c)*d)
The Postfix Expn is: abc-d*+
Program outcome :
Identify the applications of infix and postfix.
Implement C program to convert infix to postfix.
Identify the different operators.
Viva Questions:
What is a postfix expression?
What are Infix, prefix, Postfix notations?
What is the evaluation order according to which an infixexpressionis
converted to postfix expression ?
which data structure is used for infix to postfix conversion
PROGRAM 5
Design, develop and implement a Program inC for the following Stack
Applications
a. Evaluation of Suffixexpression withsingle digit operands
and operators: +, -, *, /,%, ^
b. Solving Tower of Hanoi problem with n disks
Program objective :
Understand different polish notation.
Understand the methodology of evaluating suffix expression.
Get the knowledge of operator precedence and associativity.
Algorithm
Step 1: Read the suffix/postfix expression
Step 2: Scan the postfix expression from left to right character by character
Step 3: if scanned symbol is operand push data into stack.
If scanned symbol is operator pop two elements from stack Evaluate result
and result is pushed onto stack
Step 4: Repeat step 2-3 until all symbols are scanned completely
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define MAX 50
char post[MAX];
int stack[MAX],top=-1,i;
void pushstack(int);
void calculator(char);
main()
{
printf("enter suffix expression\n");
gets(post);
for(i=0; i<strlen(post); i++)
{
if(post[i]>'0'&& post[i]<='9')
pushstack(i);
else
calculator(post[i]);
}
printf("result=%d\n",stack[top]);
}
void pushstack(int i)
{
top=top+1;
stack[top]=(int)(post[i]-48);
}
void calculator(char c)
{
int a,b,ans;
b=stack[top--];
a=stack[top--];
switch(c)
{
case '+':ans=a+b;break;
case '-':ans=a-b;break;
case '*':ans=a*b;break;
case '/':ans=a/b;break;
case '%':ans=a%b;break;
case '^':ans=pow(a,b);break;
default :printf("wrong input\n");
exit(0);
}
top++;
stack[top]=ans;
}
Output1
enter suffix expression:
23+
The result is 5
Output2
enter suffix expression:
123-4*+
The result is -3.
Output3
enter suffix expression:
623+-382/+*2$3+
The result is 52
Program outcome:
Identify the applications of suffix expression.
Familiarized with the methodology of suffix evaluation.
Familiarized the operator precedence and associativity.
Viva Questions
What is Suffix Expression?
Program objective:
Understand tower of Hanoi problem.
Understand recursive functions and its disadvantages.
Algorithm:
MAIN FUNCTION ()
Step 1: Read No of disks called n from keyboard.
Step 2: Check if n is not zero or a negative no. if yes display suitable message
else go to step3.
Step 3: Call tower of Hanoi function with n asparameter,
Step 4: Stop
THEORY
The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a
number of disks of different sizes which can slide onto any rod. The puzzle starts with the
disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making
a conical shape.
The program objective of the puzzle is to move the entire stack to another rod, obeying
the following simple rules:
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and placing it on top
of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
No disk may be placed on top of a smallerdisk.
With three disks, the puzzle can be solved in seven moves. The minimum number of moves
required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks
PROGRAM:
#include<stdio.h>
Void tower(int n,char frompeg,char topeg,char auxpeg); int
n;
void main()
{
printf("Enter the no. of discs: \n");
scanf("%d",&n);
printf("the number of moves in tower of henoi problem\n");
tower(n,'A','C','B');
}
void tower(int n,char frompeg,char topeg,char auxpeg)
{
if(n==1)
{
printf("move disk1 from %C to %C\n ",frompeg,topeg);
return;
}
tower(n-1,frompeg,auxpeg,topeg);
printf("move disk%d from %C to %C\n",n,frompeg,topeg);
tower(n-1,auxpeg,topeg,frompeg);
}
Output
Enter the no. of discs:
3
the number of moves in tower of henoi problem
Move disc 1 from A to C
Move disc 2 from A to B
Move disc 1 from C to B
Move disc 3 from A to C
Move disc 1 from B to A
Move disc 2 from B to C
Move disc 1 from A to C
DEPT OF CSE, ATMECE, MYSURU Page 39
DATA STRUCTURES LABORATORY 18CSL38
Program outcome:
Identify the application of Tower of Hanoi problem.
Implement the methodology to solve Tower of Hanoi problem.
Implement the given problem using recursive function.
Viva Questions
How do you solve the problem of the Tower of Hanoi usingrecursion?
What is recursion? And what is tower of Hanoi problem?
PROGRAM 6
Design, develop and implement 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
Program objective:
Understand the working of circularqueue
Know the advantages of circular queue over liner queue.
Understand the insertion and deletion operation oncircular queue.
Understand overflow and underflow conditions incircularqueue.
ALGORITHM:
Step1: Initialize front and rear pointer and also count
front->0,count<-0,rear<- -1
THEORY
Circular queue is a linear data structure. It follows FIFO principle. In circular queue the last
node is connected back to the first node to make a circle.
It is also called FIFO structure. Elements are added at the rear end and the elements are deleted
at front end of the queue. The queue is considered as a circular queue when the positions 0 and
MAX-1 are adjacent.
Fig6-circular queue
The limitation of simple queue is that even if there is a free memory space available in the
simple queue we cannot use that free memory space to insert element. Circular Queue is
designed to overcome the limitation of Simple Queue.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#define MAX 5
Char q[MAX],item;
int f=0,r=-1,count=0;
void insert();
void delete();
void display();
main()
{
int ch;
while(1)
{
printf("1.insert 2.delete 3.display 4.exit \n");
printf("enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:getchar();insert();
break;
case 2:delete();
break;
case 3:display();
break;
case 4:exit(0);
default :printf("Invalid choice\n");
break;
}
}
}
void insert()
{
if(count==MAX)
printf("queue overflow\n");
else
{
printf("enter the item to be inserted\n");
scanf("%c",&item );
r=(r+1)%MAX;
q[r]=item;
count++;
}
}
void delete()
{
if(count==0)
printf("queue underflow\n");
else
{
printf("deleted item is %c\n",q[f]);
f=(f+1)%MAX;
count--;
}
}
void display()
{
int j=f,i;
if(count==0)
printf("queue is empty\n");
else
{
printf("contents of circular queue\n");
for(i=1;i<=count;i++)
{
printf("%c\t",q[j]);
j=(j+1)%MAX;
}
printf("total number of items=%d\n",count);
}
}
Output
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the item to be inserted: A
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the item to be inserted: B
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the item to be inserted: C
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the item to be inserted: D
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 3
Contents of Queue is:
ABCD
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the character / item to be inserted: F
Queue is Full
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 2
Deleted item is: A
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 2
Deleted item is: B
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 3
Contents of Queue is:
CD
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the item to be inserted: K
1. Insert 2. Delete
Enter the choice: 3
Program outcome:
Identify the applications of circular queue.
Implement insert and delete operations on circular queue.
Viva Questions:
What is a queue ?what are applications of queue?
What is Circular Queue? What is the difference between a Stack and a Queue?
PROGRAM 7
Design, Develop and Implement a menu driven Program in C for the
following operations on Singly Linked List (SLL) of Student Data with the
fields: USN, Name, Branch, 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 and Deletion at End of SLL
d Perform Insertion and Deletion at Front of SLL
e Demonstrate how this SLL can be used as STACKandQUEUE
f Exit
Program objective:
Understand the Singly Linked List (SLL) data structures.
Understand the methodology to insert and delete the element at the frontof
SLL.
Understand the methodology to insert and delete the element at theendof
SLL.
Get the knowledge of how SLL and be used as both stack and queue.
Algorithm
Step 1: declare structure of node createemptylist
head->null
Step2: Insert at front end
head<-null
returntemp
if list is empty
temp->link=head
return head
Step 3:Insert at rear end
head=null
returntemp
if list is empty
cur->head
while(cur!=null)
cur=cur->link
cur->link=temp;
return head
THEORY
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.
In any single linked list, the individual element is called as "Node". Every "Node" contains two
fields, data and next. The data field is used to store actual value of that node and next field is
used to store the address of the next node in the sequence.
They are a dynamic in nature which allocates the memory when required.
Insertion and deletion operations can be easilyimplemented.
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.
Drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting fromthe
first node. So we cannot do binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void create();
void insert_front();
void insert_rear();
void display();
void delete_front();
void delete_rear();
int count=0;
struct node{
char usn[20],name[50],branch[10];
int sem;
unsigned long long int phno;
struct node *link;
};
struct node *first=NULL,*last=NULL,*temp=NULL,*p;
void main()
{
int ch,n,i;
while(1)
{
printf("1.create SLL 2.insert at front 3.insert at rear 4.display 5.delete at front 6.delete at
rear 7.exit\n");
printf("enter choice\n");
scanf("%d",&ch);
switch(ch)
{
DEPT OF CSE, ATMECE, MYSURU Page 51
DATA STRUCTURES LABORATORY 18CSL38
case 1:printf("enter the no.of students\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
insert_front();
break;
case 2:insert_front();
break;
case 3:insert_rear();break;
case 4:display();break;
case 5:delete_front();break;
case 6:delete_rear();break;
case 7:exit(0);
default:printf("invalid choice\n");break;
}
}
}
void create()
{
char usn[20],name[50],branch[10];
int sem;
unsigned long long int phno;
temp=(struct node*)malloc(sizeof(struct node));
printf("enter usn,name,branch,sem,phno\n");
scanf("%s%s%s%d%llu",usn,name,branch,&sem,&phno);
strcpy(temp->usn,usn);
strcpy(temp->name,name);
strcpy(temp->branch,branch);
temp->sem=sem;
temp->phno=phno;
count++;
DEPT OF CSE, ATMECE, MYSURU Page 52
DATA STRUCTURES LABORATORY 18CSL38
}
void insert_front()
{
if(first==NULL)
{
create();
temp->link=NULL;
first=temp;
last=temp;
}
else
{
create();
temp->link=first;
first=temp;
}
}
void insert_rear()
{
if(first==NULL)
{
create();
temp->link=NULL;
first=temp;
last=temp;
}
else
{
create();
Output
MENU-
Enter choice :
2
List empty to display
MENU-
Enter choice :1
Enter no of students :
2
MENU-
Enter choice :
2
MENU-
Enter choice :
2
7 - exit
MENU-
Enter choice :
2
MENU-
Enter choice :
4
4ad16cs011 bharath cs 3 9912698467
MENU-
Enter choice :
2
MENU-
1 create a SLL of n emp
2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
Enter choice :
6
4ad16cs033 jayakumar cs 3 8903478345
MENU-
Enter choice :
2
MENU-
Enter choice :
8
wrong choice
MENU-
Enter choice :
7
Program outcome :
Implement Singly Linked List.
Implement insertion at the front and end of SLL.
Implement deletion at the front and end of SLL.
Identify the applications of SLL.
Familiarized how SLL can be used as both stack and queue.
Viva Questions :
What is a Linked List and What are its types? What is a node?
What are the parts of a linked list? What are the advantages of linked list?
Mention what is traversal in linked lists?
PROGRAM 8
Design, Develop and Implement 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
Program objective:
Understand the Doubly Linked List (DLL) data structures.
Understand the methodology to insert and delete the element at the frontof
DLL.
Understand the methodology to insert and delete the element at the endof
DLL.
Get the knowledge of how DLL and be used as double ended queue.
Algorithm
Insertion at front end of list.
Step 1: Allocate memory for temp node and assign values to node
Step2: if list is empty, temp is attached to list directly
head=null
returntemp
if list is not empty
temp->rlink=head
head->llink=temp
return head
return head;
Step 2: Traverse the cur node upto end of list before updating current pointer save
the
Address to prev pointer.
While(cur->rlink!=null)
{
prev=cur;
cur=cur->rlink;
}
prev->rlink=null;
cur->llink=null;
free(cur);
THEORY
In computer science, a doubly linked list is a linked data structure that consists of a set
of sequentially linked records called nodes.
Each node contains two fields, called links, that are references to the previous and to
the next node in the sequence of nodes. The beginning and ending nodes' previous and
next links, respectively, point to some kind of terminator, typically a sentinel node or
null, to facilitate traversal of the list. If there is only one sentinel node, then the list is
circularly linked via the sentinel node. It can be conceptualized as two singly linked
lists formed from the same data items, but in opposite sequential orders.
A doubly linked list whose nodes contain three fields: an integer value, the link to the
next node, and the link to the previous node.
The two node links allow traversal of the list in either direction. While adding or
removing a node in a doubly linked list requires changing more links than the same
operations on a singly linked list, the operations are simpler and potentially more
efficient (for nodes other than first nodes) because there is no need to keep track of the
previous node during traversal or no need to traverse the list to find the previous node,
so that its link can be modified.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void create();
void insert_front();
void insert_rear();
void display();
void delete_front();
void delete_rear();
int count=0;
struct node
{
int ssn;
char name[50],dept[20],desg[20];
float sal;
unsigned long long int phno;
struct node *llink,*rlink;
};
struct node *first=NULL,*last=NULL,*temp;
main()
{
int ch,n,i;
while(1)
{
printf("1.create\n 2.insert_front\n 3.insert_rear\n 4.display\n 5.delete_front\n 6.delete_rear\n
7.exit\n");
printf("enter choice\n");
Output
MENU-
Enter choice :
2
List empty to display
MENU-
Enter choice :
1
Enter no of employees :
2
Enter ssn,name,department, designation, salary and phno ofemployee :
120 harsha cs instructor 14000 9912378956
MENU-
Enter choice :
2
MENU-
MENU-
Enter choice :
2
Enter choice :
5
MENU-
Enter choice :
2
MENU-
MENU-
Enter choice :
2
MENU-
Enter choice :
6
MENU-
Enter choice :
2
MENU-
Enter choice :
7
$
Program outcome:
Implement Doubly Linked List.
Implement insertion at the front and end of DLL.
Implement deletion at the front and end of DLL.
Identify the applications of DLL.
Familiarized how DLL can be used as double ended queue.
Viva Questions:
What are doubly linked lists?
What is the difference between singly and doubly linked lists?
What are the advantages of double linked list over single linked list?
PROGRAM 9
Design, Develop and Implement a Program in C for the following operations
on Singly Circular Linked List (SCLL) with header nodes
a Represent and Evaluate a Polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-
2xyz3
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)
Program objective: .
Understand the working of Singly Circular Linked List (SCLL).
Understand the use of header nodes.
Understand the methodology to evaluate polynomial usingSCLL.
Understand the methodology to add twopolynomialusingSCLL.
Algorithm:
Evaluate a Polynomial
Step1: allocate memory for newly created node assign values to that node
Step 2: attach newly created node to list in circular fashion.
Step3: Evaluate each node information up to header node
THEORY
Circular Linked List:
In the circular linked list the last node of the list contains the address of the first node
and forms a circular chain.
Circular Linked List is a variation of Linked list in which the first element points to the
last element and the last element points to the first element. Both Singly Linked List and
Doubly Linked List can be made into a circular linked list.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct node
{
int co,ex,ey,ez;
struct node *link;
};
typedef struct node NODE;
NODE *createnode(int,int,int,int);
NODE *attachnode(NODE*,NODE*);
NODE *readpoly();
void display(NODE*);
void evaluate(NODE*);
NODE *addpoly(NODE*,NODE*,NODE*);
temp=(NODE*)malloc(sizeof(NODE));
temp->co=co;
temp->ex=ex;
temp->ey=ey;
temp->ez=ez;
temp->link=NULL;
return temp;
}
head->link=head;
printf("enter the number of terms\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("term %d\n",i+1);
printf("enter the coefficient\n");
scanf("%d",&co);
printf("enter exponent values of x,yand z\n");
scanf("%d%d%d",&ex,&ey,&ez);
temp=createnode(co,ex,ey,ez);
head=attachnode(temp,head);
}
return head;
}
while(cur!=poly)
{
printf("%dx^%dy^%dz^%d+",cur->co,cur->ex,cur->ey,cur->ez);
cur=cur->link;
}
printf("\n");
}
res+=cur->co*pow(x,cur->ex)*pow(y,cur->ey)*pow(z,cur->ez);
cur=cur->link;
}
printf("result=%d\n",res);
}
b=b->link;
break;
case 1:temp=createnode(a->co, a->ex,a->ey,a->ez);
poly=attachnode(temp,poly);
a=a->link;
break;
case-1:temp=createnode(b->co,b->ex,b->ey,b->ez);
poly=attachnode(temp,poly);
b=b->link;
break;
}
}
while(a!=p1)
{
temp=createnode(a->co,a->ex,a->ey,a->ez);
poly=attachnode(temp,poly);
a=a->link;
}
while(b!=p2)
{ temp=createnode(b->co,b->ex,b->ey,b->ez);
poly=attachnode(temp,poly);
b=b->link;
}
return poly;
}
main()
{
int ch;
NODE *p1,*p2,*p3;
p3=(NODE*)malloc(sizeof(NODE));
p3->link=p3;
while(1)
{
printf("1.represent and evaluate 2.add two polynomial 3.exit\n");
printf("enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("enter a polynomial\n");
p1=readpoly();
display(p1);
evaluate(p1);
break;
case 2:printf("enter polynomial 1\n");
p1=readpoly();
display(p1);
printf(" enter polynomial 2\n");
p2=readpoly();
display(p2);
p3=addpoly(p1,p2,p3);
printf("the resultant polynomial is\n");
display(p3);
break;
case 3:exit(0);
default:printf("invalid choice\n");
break;
}
}}
Output
<< MENU >>
Polynomial Operations : 1.Add 2.Evaluate
3.Exit
Enter your choice==>1
Enter no of terms of polynomial==>3
Enter coef& expo==>
4
3
Enter coef& expo==> 22
Enter coef& expo==> 51
The polynomial is==>5x^(1) + 2x^(2) + 4x^(3)
Enter no of terms of polynomial==>3
Enter coef& expo==> 4 1
Enter coef& expo==>
3
2
Enter coef& expo==> 5 3
The polynomial is==>4x^(1) + 3x^(2) + 5x^(3)
Addition of polynomial==>
The polynomial is==>9x^(1) + 5x^(2) + 9x^(3)
Enter your choice==>2
Enter no of terms of polynomial==>3
Enter coef& expo==>
3
1
Program outcome :
Implement Singly Circular Linked List (SCLL) using header node.
Identify the application of SCLL.
Familiarized withthe methodology ofpolynomial evaluation andpolynomial
addition using SCLL.
Viva Questions:
What is circular linked list.?
What are Advantages and Disadvantages of Circular Linked List?
PROGRAM 10
Design, Develop and Implement 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 In-order, Preorder and PostOrder
C Searchthe BST for a givenelement (KEY) and reportthe appropriate
message
D Delete anelement (ELEM) from BST
E Exit
Program objective:
Understand the concept of Binary Search Tree (BST).
Understand the different traversal method on BST.
Get to know the methodology of searching a key element in BST.
Understand the methodology of deleting an element from BST.
Algorithm:
Preorder Traversal
Step 1: Display root information
Step2: Traverse left sub tree in preorder
Step 3: Traverse right sub tree in preorder
In order Traversal
Step 1: Traverse the left sub tree in order
Step 2: Display root information
Step3: Traverse right sub tree in order
THEORY
A binary search tree (BST) is a tree in which all nodes follows the below mentioned properties
The left sub-tree of a node has key less than or equalto its parent node’s V key.
The right sub-tree of a node has key greater than or equal to its parent node'skey.
Thus, a binary search tree (BST) divides all its sub-trees into two segments; left sub-tree and
right sub-tree and can be defined as
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
typedef struct bst
{
int data;
struct bst *rchild,*lchild;
}node;
node* getnode();
void insert(node*,node*);
void inorder(node*);
void preorder(node*);
void postorder(node*);
int search(node*,int);
int n;
node* getnode()
{
node *temp;
temp=(node*)malloc(sizeof(node));
temp->lchild=NULL;
temp->rchild=NULL;
return temp;
}
void main()
{
int ch;
int key,ans=1;
node *newnode,*root,*temp,*parent;
root=NULL;
while(1)
{
printf("1.create 2.search 3.travers 4.exit\n");
printf("enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:while(ans==1)
{
newnode=getnode();
printf("enter the element\n");
scanf("%d",&newnode->data);
if(root==NULL)
root=newnode;
else
insert(root,newnode);
printf("want to continue[0/1]\n");
scanf("%d",&ans);
}
break;
case 2:printf("enter the element to search\n");
scanf("%d",&key);
search(root,key);
if(n==1)
printf("search successful\n");
else
printf("search unsuccessful\n");
break;
case 3:if(root==NULL)
printf("tree is empty\n");
else
{
printf("\n inorder traversal\n");
inorder(root);
printf("\n postorder traversal\n");
postorder(root);
printf("\n preorder traversal\n");
preorder(root);
}
break;
case 4:exit(0);break;
default :printf("wrong choice\n");
break;
}
}
}
void insert(node *root,node *newnode)
{
if(root->data<newnode->data)
{
if(root->rchild==NULL)
root->rchild==newnode;
else
insert(root->rchild,newnode);
}
else
{
if(root->lchild==NULL)
root->lchild=newnode;
else
insert(root->lchild,newnode);
}
}
void inorder(node *ptr)
{
if(ptr!=NULL)
{
inorder(ptr->lchild);
printf("%d\t",ptr->data);
inorder(ptr->rchild);
}
}
void preorder(node*ptr)
{
if(ptr!=NULL)
{
printf("%d\t",ptr->data);
preorder(ptr->lchild);
preorder(ptr->rchild);
}
}
void postorder(node *ptr)
{
if(ptr!=NULL)
{
postorder(ptr->lchild);
postorder(ptr->rchild);
printf("%d\t",ptr->data);
}
}
int search(node*root,int key)
{
node *temp;
temp=root;
if(root!=NULL)
{
if(temp->data==key)
n=1;
else if (key>temp->data)
search(temp->rchild,key);
else
search(temp->lchild,key);
}
else n=0;
return n;
}
Output
program for binary search tree
1.Create
2. Search
3. RecursiveTraversals
4.Exit
Enter your Choice= 1
Enter the element=15
Want to entermoreelements?(1/0)1
Enter the element=25
Want to entermoreelements?(1/0)1
Enter the element=35
Want to entermoreelements?(1/0)1
Enter the element=45
Want to entermoreelements?(1/0)1
Enter the element=5
Want to entermoreelements?(1/0)1
Enter the element=7
Want to enter more elements?(1/0)0
1.Create
2. Search
3. RecursiveTraversals
4.Exit
Enter your choice=2
Enter elements to be searched=7
The 7 element is present
parent of node 7 is 5
1.Create
2. Search
3. RecursiveTraversals
4.Exit
Enter your choice=2
Enter elements to be searched=88
the 88 element is not present
1.Create
2.Search
3.Recursive Traversals
4.Exit
Enter your choice=3
The inorder display =5 7 15 25 35 45
The preorder display=15 5 7 25 35 45
The postorder display=7 5 45 35 25 15
1.Create
2. Search
3. RecursiveTraversals
4.Exit
Enter your choice=4
Program outcome:
Implement Binary Search Tree (BST).
Implement the different traversal methodology on BST.
Familiarized with the methodology to search a key element in BST.
Implement the methodology to delete an element from BST.
Identify the applications of BST
Viva Questions:
What are binary trees?
Explain Binary Search Tree
How to check if a given Binary Tree is BST or not?
What is the minimum number of nodes that a binary tree can have?
What are the different types of traversing?
Define pre-order traversal?
Define post-order traversal?
Define in -order traversal?
PROGRAM 11
Design, develop and implement 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 ina digraph
using BFS method
c Check whether a given graph is connected or notusingDFS
Method.
Program objective:
Understand the concept of trees and adjacency matrix.
Understand the concept of connected graph.
Understand the Breath First Search(BFS) and Depth First Search(DFS)
traversal methodologies.
Algorithm:
THEORY
BFS first visits all the vertices that are adjacent to a starting vertex. Every time it adds the
adjacent vertex to a queue array q. On each successive iteration of the algorithm, the next
vertex on the queue is examined to see if there are any unvisited vertices adjacent to it which
can be added to the queue. Whenever a new vertex is taken from the queue, it is marked as a
visited node in the visited array.
Applications of BFS:
To check connectivity of a graph (number of times queue becomes emptytellsthe
number of components in thegraph)
To check if a graph is acyclic. (no cross edges indicates no cycle)
To find minimum edge path in a graph
Depth first search is a graph algorithm required for processing vertices or edges of a
graph in a systematic fashion. Depth first search starts visiting vertices of a graph at an
arbitrary vertex by marking it as having been visited. On each iteration, the algorithm proceeds
to an unvisited vertex that is adjacent to one it is currently in.
The algorithm backs up one edge to the vertex it came from and tries to continue
visiting unvisited vertices from there. The algorithm eventually halts after backing up to
starting vertex, with the latter being dead end. By then, all vertices in the same connected
component as the starting vertex have been visited. If unvisited vertices still remain, the depth
first search must be restarted at any one of them.
Here we use a STACK to trace the depth first search. We push a vertex onto the stack
when the vertex is reached for the first time, and we pop a vertex off the stack when it
becomes a dead end.
Applications of DFS:
The two orderings are advantageous for various applications liketopologicalsorting,
etc.
To check connectivity ofa graph (number oftimes stack becomes emptytells the
number of components in thegraph)
To check if a graph is acyclic. (no back edges indicates no cycle)
To find articulation point in a graph
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int n,a[10][10],i,j,source,s[10],choice,count;
void bfs(int n,int a[10][10],int source,int s[])
{
int q[10],u;
int front=1,rear=1;
s[source]=1;
q[rear]=source;
while(front<=rear)
{
u=q[front];
front=front+1;
for(i=1;i<=n;i++)
if(a[u][i]==1 &&s[i]==0)
{
rear=rear+1;
q[rear]=i;
s[i]=1;
}
}
}
void dfs(int n,int a[10][10],int source,int s[])
{
s[source]=1;
for(i=1;i<=n;i++)
if(a[source][i]==1 && s[i]==0)
dfs(n,a,i,s);
}
int main()
{
printf("Enter the number of nodes : \n");
scanf("%d",&n);
printf("\n Enter the adjacency matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
while(1)
{
}
}
}
Output1
1. BFS
2. DFS
3. Exit
1. BFS
2. DFS
3. Exit
1.BFS
2. DFS
3. Exit
enter your choice
3
Output2
1. BFS
2. DFS
3. Exit
1. BFS
2. DFS
3. Exit
1.BFS
2. DFS
3. Exit
Output3
1. BFS
2. DFS
3. Exit
1. BFS
2. DFS
3. Exit
1.BFS
2. DFS
3. Exit
Program outcomes:
Create graph using adjacency matrix.
Implement Breadth First Search (BFS) and Depth First Search(DFS).
Familiarized with connected graph.
Identify the applications of graphs.
Viva Questions:
What is a graph?
What is a tree?
What is BFS and DFS?
Which data structures are used for BFS and DFS of a graph?
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 mmemory 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.
Design and 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.
Program objective:
Understand what is hashing and hashing function.
Understand the concept of linear probing.
Understand the concept ofcollision detectionand avoidance usinglinear
probing.
Algorithm:
Step 1: Start
Step 2: Initialize all memory locations with some values to identity as space
a[i]=-1
Step 3: Read Employee key value .calculate hash key using remainder method
hk<-key%100
Step 4: Inserting Employee record using key
Inserting hash dull function
If(count=m)
If space is available for that key
If(H[k]==-1)
H[hk] <-key
If collision occurs, it can be solved using linear probing method.
Checking free space from key to end
for(i=hk+1;i<m;i++)
Checking free space from beginning to key value.
for(i=0;i<hk&& flag==0;i++)
Step 5: Display all memory location with index and employee key
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
void display(int a[MAX]);
int create(int num);
void linearprob(int a [MAX],int key,int num);
void main()
{
int a[MAX],i,num,key,ans=1;
printf("collission handling by linear probing\n");
for(i=0;i<MAX;i++)
a[i]= -1;
do
{
printf("enter the data\n");
scanf("%4d",&num);
key=create(num);
linearprob(a,key,num);
printf("do yuou want to continue[1/0]\n");
scanf("%d",&ans);
}while(ans);
display(a);
}
int create(int num)
{
int key;
key=num%100;
return key;
}
else
{
for(i=0;i<MAX;i++)
{
if(a[i]!=-1)
{
printf("%d\t %d\n",i,a[i]);
continue;
}
}
}
}
Output
collision handling by linear probing :
Enter the data1234
Do you wish to continue ? (1/0)1
Enter the data2548
Do you wish to continue ? (1/0)1
Enter the data3256
Do you wish to continue ? (1/0)1
Enter the data1299
Do you wish to continue ? (1/0)1
Enter the data1298
Do you wish to continue ? (1/0)1
Enter the data1398
Collision Detected...!!!
Collision avoided successfully using LINEAR PROBING
Do you wish to continue ? (1/0) 0
1.Display ALL
2.Filtered Display
the hash table is
0 1398
341234
482548
563256
981298
991299
Program outcome:
Implement hashing function.
Implement linear probing.
Familiarized the concept ofcollusion detectionand avoidance and detection
using linear probing.
Identify the application of hashing and linear probing.
Viva Questions:
What is Hashing?
What is Linear Probing?
Basic Concepts
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.
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.
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 non linear 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.
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.1 2 3 4 5
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.
APPLICATION OF QUEUE
Queue, as the name suggests is used whenever we need to have any group of objects in an
order in which the first one coming in, also gets out first while the others wait for their turn,
like in the following scenarios :
Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
In real life, Call Center phone systems will use Queues, to hold people calling them in an
order, until a service representative is free.
Handling of interrupts in real-time systems. The interrupts are handled in the same order as
they arrive, First come first served.
LINKED LIST
Disadvantages of static/sequential allocation technique:
If an item has to be deleted then all the following items will have to be moved by one
allocation. Wastage of time.
Inefficient memory utilization.
If no consecutive memory (free) is available, execution is not possible.
NODE:
Each node consists of two fields. Information (info) field and next address (next) field. The
info field consists of actual information/data/item that has to be stored in a list. The second
field next/link contains the address of the next node. Since next field contains the address,
It is of type pointer. Here the nodes in the list are logically adjacent to each other. Nodes that
are physically adjacent need not be logically adjacent in the list.
The entire linked list is accessed from an external pointer FIRST that points to (contains the
address of) the first node in the list. (By an “external” pointer, we mean, one that is not
included within a node. Rather its value can be accessed directly by referencing a variable).
As each node is having only one link/next, the list is called single linked list and all the
nodes are linked in one direction. Each node can be accessed by the pointer pointing (holding
the address) to that node, Say P is pointer to a particular node, then the information field of that
node can be accessed using info(P) and the next field can be accessed using next(P).
The arrows coming out of the next field in the fig. indicates that the address of the
succeeding node is stored in that field. The link field of last node contains a special value
known as NULL which is shown using a diagonal line pictorially. This NULL pointer is used
to signal the end of a list.
The basic operations of linked lists are Insertion, Deletion and Display. A list is a
dynamic data structure. The number of nodes on a list may vary dramatically as elements are
inserted and deleted(removed).
The dynamic nature of list may be contrasted with the static nature of an array, whose
size remains constant. When an item has to inserted, we will have to create a node, which has
to be got from the available free memory of the computer system, So we shall use a mechanism
to find an unused node which makes it available to us. For this purpose we shall use the
getnode operation (getnode() function).
The C language provides the built-in functions like malloc(), calloc(), realloc() and
free(), which are stored in alloc.h or stdlib.h header files. To dynamically allocate and release
the memory locations from/to the computer system.
TREES:
Definition:
A data structure which is accessed beginning at the root node. Each node is either a
leaf or an internal node. An internal node has one or more child nodes and is called the parent
of its child nodes. All children of the same node are siblings. Contrary to a physical tree, the
root is usually depicted at the top of the structure, and the leaves are depicted at the bottom. A
tree can also be defined as a connected, acyclic di-graph.
Tree is a non-linear data structure which organizes data in hierarchical structure and this is a
recursive definition.
A tree data structure can also be defined as follows...
Tree data structure is a collection of data (Node) which is organized in hierarchical structure
and this is a recursive definition
Binary tree: A tree with utmost two children for each node.
Complete Binary Tree: A binary tree in which every level, except possibly the deepest, is
completely filled. At depth n, the height of the tree, all nodes must be as far left as possible.
Binary search tree: A binary tree where every node’s left subtree has keys less than the node's
key, and every right subtree has keys greater than the node's key.
Tree traversal is a technique for processing the nodes of a tree in some order.The
different tree traversal techniques are Pre-order, In-order and Post-order traversal.In Pre-order
traversal, the tree node is visited first and the left subtree is traversed recursively and later right
sub-tree is traversed recursively.
PROGRAM 1
Design, Develop and Implement a menu driven Program in C for the
following Array operations
a. Creating an Array of N Integer Elements
b. Display of Array Elements with Suitable Headings
c. Inserting an Element (ELEM) at a given valid Position (POS)
d. Deleting an Element at a given valid Position(POS)
e. Exit.
Support the program with functions for each of the above operations
Program objective:
Understand the working of array datastructures.
Understand the use of functions to implement each arrayoperation.
Understand what is menu driven program and how to implement it.
Algorithm:
Step 1: Start.
Step 2: Read number of elements.(n)
Step 3: Read Array of N integerelements
Step 4: Display array contents and checking array empty condition
Step 5: Read valid position, to insert element into that position
Step 6: Delete an element at given valid position from an array.
Step 7: Stop
THEORY:
Array is a collection of elements of the same type. In this program we need to use functions for
various operations
Create (): Create an array for the size given by the user
Display (): Display the elements of the array
Insert (): Insert an element at the position given by the user
Delete (): Delete an element from the position specified by the user
Exit (): Terminate
Arrays are the kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an arrayas a collection of variables of the sametype.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows –
type array Name [ arraySize ];
This is called a single-dimensional array. The array Size must be an integer constant
greater than zero and type can be any valid C data type.
For example, to declare a 10-element array called balance of type double, use this statement –
double balance [10];
You can initialize an array in C either one by one or using a single statement as follows –
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
#include<stdio.h>
#include<stdlib.h>
int a[20],n,i,por,val,choice;
void create();
void display();
void insert();
void delete();
void main()
{
while(1)
{
printf("....MENU...|n");
printf("1.create\n 2.display\n 3.insert\n 4.delete\n 5.exit\n");
printf("enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:create();
break;
case 2:display();
break;
case 3:insert();
break;
case 4:delete();
break;
case 5:exit(0);
break;
default:printf("invalid choice\n");
break;
}
}
}
void create()
{
printf("enter the number of elements\n");
scanf("%d",&n);
DEPT OF CSE, ATMECE, MYSURU Page 8
DATA STRUCTURES LABORATORY 18CSL38
Output
Program outcome:
Implement the menu driven C program using switchstatement.
Implement an array of any size and all the possible operations onarray.
Identify the different applications where arrays can be used.
Familiarized with the usage of functions in program.
Viva Questions:
What is a array?
What is two dimensional array?
How to access elements of array?
Can you change size of array once created?\
What is two dimensional array?
How An array elements are always stored in memory locations.?
PROGRAM 2
Design, develop and implement 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
Program objective:
Understand the implementation of string function’s using arrays.
Understand pattern matching algorithm and theimplementationtechniqueof
the same without using built-in functions.
Understand the pattern replacement methodology.
Algorithm:
Step 1: Start.
Step 2: Read main string STR, pattern string PAT and replace string REP.
Step 3: compare pattern string in main string,
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.
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."
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:
PROGRAM:
#include<stdio.h>
void read();
void match();
char STR[100],PAT[100],REP[100],ANS[100];
int c,i,j,k,m,flag=0;
main()
{
read();
match();
}
void read()
{
printf("enter the main string STR:");
gets(STR);
printf("enter pattern string PAT:");
gets(PAT);
printf("enter replace string REP:");
gets(REP);
}
void match()
{
c=i=j=k=m=0;
while(STR[c]!='\0')
{
if(STR[m]==PAT[i])
{
i++;m++;
flag=1;
if(PAT[i]=='\0')
{
for(k=0;REP[k]!='\0';k++,j++)
ANS[j]=REP[k];
i=0;
DEPT OF CSE, ATMECE, Mysuru Page 16
DATA STRUCTURES LABORATORY 18CSL38
c=m;
}
}
else
{
ANS[j]=STR[c];
j++;c++;
m=c;
i=0;
}
}
if(flag==0)
printf("pattern not found");
else
{
ANS[j]='\0';
printf("resultant string is %s",ANS);
}
}
Output 1
Enter the MAIN string:
atme college of engg
Enter a PATTERN string:
engg
Enter a REPLACE string:
engineering
The RESULTANT string is: atme college of engineering
Output 2
Enter the MAIN string:
atme college of engg
Enter a PATTERN string:
for
Enter a REPLACE string:
if
Pattern doesn't found!!!
Output 3
Enter the MAIN string:
This is Data Structure lab
Enter a PATTERN string:
Data Structure
Enter a REPLACE string:
Data structure with C
The RESULTANT string is: This is Data structure with C lab
Program outcomes:
Implement string matchingand string replacement algorithmwithout using
built-in library functions.
Apply the knowledge of array usage to implement string functions.
Identify different applications of string matching andstringreplacement.
Viva Questions:
What is a string?
How strings are represented in C language? What does strlen do in C?
Is there a string data type in C? What is the use of char in Cprogramming?
PROGRAM 3
Design, Develop and Implement 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 ontoStack
b Pop an Element fromStack
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.
Program objective:
Understand the concept of palindrome.
Understand the stack data structures.
Understand the different functions onstacks i.e., push, pop and implement the
same.
Understand stack overflow and underflow.
Algorithm:
PUSH (item)
Step 1: Read an element to be pushed on to stack item
Step 2: check overflow condition of stack before inserting element into
stack Top=max-1
Step 3: update the top pointer and insert an element into stack
Top=top+1
S[top] <-item
POP (item)
Step1: check underflow condition of stack before deleting element from stack
top=-1
Step2: Display deleted element pointed by top
Deleted element<- s[top]
Step3: Decrement top pointer by 1
top<-top-1
Palindrome
Step 1: Two pointers are required , one is pointed to top of stack
another is bottom of stack
Step 2: compare top and bottom elements of stack if it is equal update top and
bottom pointer by1
Step 3: if all elements are equal, then stack content is palindrome
THEORY
It is called as last in, first out. The element inserted first is the last one to be deleted. It
is used for various applications like infix to postfix expression, postfix evaluation and for
maintaining stack frames for function calling
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.
Fig4-Example of Stack
A stack can be implemented by means of Array, Structure, Pointer and Linked-List. Stack
can either be a fixed size one or it may have a sense of dynamic resizing.
Here, we are going to implement stack using arrays which makes it a fixed size stack
implementation.
#include<stdio.h>
#include<stdlib.h>
#define MAX 4
int stack[MAX],top=-1,item;
void push();
void pop();
void palindrome();
void display();
void main()
{
int choice;
while(1)
{
Printf(“------- STACK OPERATIONS ------ \n“);
printf("1.push\n 2.pop\n 3.palindrome\n 4.display\n 5.exit\n");
printf("enter choice");
scanf("%d",&choice);
switch(choice)
{
case 1:push();
break;
case 2:pop();
break;
case 3:palindrome();
break;
case 4:display();
break;
case 5:exit(0);
break;
default:printf("invalid choice\n");
break;
}
}
}
void push()
{
if(top==MAX-1)
printf("stack overflow");
else
{
printf("enter the item to be pushed\n");
scanf("%d",&item);
top=top+1;
stack[top]=item;
}
}
void pop()
{
if(top==-1)
printf("stack underflow");
else
{
item=stack[top];
top=top-1;
printf("deleted item is %d",item);
}
}
void display()
{
int i;
if(top==-1)
printf("stack is empty");
else
{
for(i=top;i>=0;i--)
printf("%d\t",stack[i]);
}
}
Output
Viva Questions:
What is Stack and where it can be used?
What is the difference between PUSH and POP?
Differentiate STACK from ARRAY.
What is the difference between a stack and a Queue?
PROGRAM 4
Design, develop and implement 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.
Program objective:
Understand different notations to represent regular expression.
Understand infix to postfix conversion.
Understand the precedence of operators.
Algorithm:
Step 1: Read the infix expression as a string.
Step 2: Scan the expression character by character till the end. Repeat the
following operations
1. If it is an operand add it to the postfixexpression.
2. If it is a left parenthesis push it onto the stack.
3. If it is a right parentheses pop out elements from the stack and assign it to
the postfix string. Pop out the left parentheses but don’t assign topostfix.
Step 3: If it is an operator compare its precedence with that of the element at the
top of stack.
1. If it is greater push it onto the stack.
2. Else pop and assignelements in the stack to the postfixexpression until
you find one such element.
Step 4: If you have reached the end of the expression, pop out any leftover
elements in the stack till it becomes empty.
Step 5: Append a null terminator at the end display the result
THEORY
Infix: Operators are written in-between their operands. Ex: X + Y
Prefix: Operators are written before their operands. Ex: +X Y postfix: Operators are written
after their operands. Ex: XY+
Step 5. Result
+*+A^BCD^E5
PROGRAM:
#include<stdio.h>
#include<ctype.h>
#define SIZE 50
char s[SIZE];
int top=-1;
void push(char elem)
{
s[++top]=elem;
}
char pop()
{
return s[top--];
}
int pr(char elem)
{
switch(elem)
{
case '#':return 0;
case '(':return 1;
case '+':
case '-':return 2;
case '*':
case '/':
case '%':return 3;
case '^':return 4;
}
}
void main()
{
char infix[50],postfix[50],ch,elem;
int i=0,k=0;
printf("enter the infix expression\n");
gets(infix);
push('#');
while((ch=infix[i++])!='\0')
DEPT OF CSE, ATMECE, MYSURU Page 31
DATA STRUCTURES LABORATORY 18CSL38
{
if(ch=='(')
push(ch);
else if(isalnum(ch))
postfix[k++]=ch;
else if(ch==')')
{
while(s[top]!='(')
postfix[k++]=pop();
elem=pop();
}
else
{
while(pr(s[top])>=pr(ch))
postfix[k++]=pop();
push(ch);
}
}
while(s[top]!='#')
postfix[k++]=pop();
postfix[k]='\0';
printf("infix expression is %s\n postfix expression is %s\n",infix,postfix);
}
Output1
enter the Infix Expression
((a+b)*c)
Given Infix Expn is: ((a+b)*c)
The Postfix Expn is: ab+c*
Output 2
enter the Infix Expression
(a+ (b-c)*d)
Given Infix Expn is: (a+ (b-c)*d)
The Postfix Expn is: abc-d*+
Program outcome :
Identify the applications of infix and postfix.
Implement C program to convert infix to postfix.
Identify the different operators.
Viva Questions:
What is a postfix expression?
What are Infix, prefix, Postfix notations?
What is the evaluation order according to which an infixexpressionis
converted to postfix expression ?
which data structure is used for infix to postfix conversion
PROGRAM 5
Design, develop and implement a Program inC for the following Stack
Applications
a. Evaluation of Suffixexpression withsingle digit operands
and operators: +, -, *, /,%, ^
b. Solving Tower of Hanoi problem with n disks
Program objective :
Understand different polish notation.
Understand the methodology of evaluating suffix expression.
Get the knowledge of operator precedence and associativity.
Algorithm
Step 1: Read the suffix/postfix expression
Step 2: Scan the postfix expression from left to right character by character
Step 3: if scanned symbol is operand push data into stack.
If scanned symbol is operator pop two elements from stack Evaluate result
and result is pushed onto stack
Step 4: Repeat step 2-3 until all symbols are scanned completely
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define MAX 50
char post[MAX];
int stack[MAX],top=-1,i;
void pushstack(int);
void calculator(char);
main()
{
printf("enter suffix expression\n");
gets(post);
for(i=0; i<strlen(post); i++)
{
if(post[i]>'0'&& post[i]<='9')
pushstack(i);
else
calculator(post[i]);
}
printf("result=%d\n",stack[top]);
}
void pushstack(int i)
{
top=top+1;
stack[top]=(int)(post[i]-48);
}
void calculator(char c)
{
int a,b,ans;
b=stack[top--];
a=stack[top--];
switch(c)
{
case '+':ans=a+b;break;
case '-':ans=a-b;break;
case '*':ans=a*b;break;
case '/':ans=a/b;break;
case '%':ans=a%b;break;
case '^':ans=pow(a,b);break;
default :printf("wrong input\n");
exit(0);
}
top++;
stack[top]=ans;
}
Output1
enter suffix expression:
23+
The result is 5
Output2
enter suffix expression:
123-4*+
The result is -3.
Output3
enter suffix expression:
623+-382/+*2$3+
The result is 52
Program outcome:
Identify the applications of suffix expression.
Familiarized with the methodology of suffix evaluation.
Familiarized the operator precedence and associativity.
Viva Questions
What is Suffix Expression?
Program objective:
Understand tower of Hanoi problem.
Understand recursive functions and its disadvantages.
Algorithm:
MAIN FUNCTION ()
Step 1: Read No of disks called n from keyboard.
Step 2: Check if n is not zero or a negative no. if yes display suitable message
else go to step3.
Step 3: Call tower of Hanoi function with n asparameter,
Step 4: Stop
THEORY
The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a
number of disks of different sizes which can slide onto any rod. The puzzle starts with the
disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making
a conical shape.
The program objective of the puzzle is to move the entire stack to another rod, obeying
the following simple rules:
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and placing it on top
of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
No disk may be placed on top of a smallerdisk.
With three disks, the puzzle can be solved in seven moves. The minimum number of moves
required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks
PROGRAM:
#include<stdio.h>
Void tower(int n,char frompeg,char topeg,char auxpeg);
int n;
void main()
{
printf("Enter the no. of discs: \n");
scanf("%d",&n);
printf("the number of moves in tower of henoi problem\n");
tower(n,'A','C','B');
}
void tower(int n,char frompeg,char topeg,char auxpeg)
{
if(n==1)
{
printf("move disk1 from %C to %C\n ",frompeg,topeg);
return;
}
tower(n-1,frompeg,auxpeg,topeg);
printf("move disk%d from %C to %C\n",n,frompeg,topeg);
tower(n-1,auxpeg,topeg,frompeg);}
Output
Enter the no. of discs:
3
the number of moves in tower of henoi problem
Move disc 1 from A to C
Move disc 2 from A to B
Move disc 1 from C to B
Move disc 3 from A to C
Move disc 1 from B to A
Move disc 2 from B to C
Move disc 1 from A to C
Program outcome:
Identify the application of Tower of Hanoi problem.
Implement the methodology to solve Tower of Hanoi problem.
Implement the given problem using recursive function.
Viva Questions
How do you solve the problem of the Tower of Hanoi usingrecursion?
What is recursion? And what is tower of Hanoi problem?
PROGRAM 6
Design, develop and implement 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
Program objective:
Understand the working of circularqueue
Know the advantages of circular queue over liner queue.
Understand the insertion and deletion operation oncircular queue.
Understand overflow and underflow conditions incircularqueue.
ALGORITHM:
Step1: Initialize front and rear pointer and also count
front->0,count<-0,rear<- -1
THEORY
Circular queue is a linear data structure. It follows FIFO principle. In circular queue the last
node is connected back to the first node to make a circle.
It is also called FIFO structure. Elements are added at the rear end and the elements are deleted
at front end of the queue. The queue is considered as a circular queue when the positions 0 and
MAX-1 are adjacent.
Fig6-circular queue
The limitation of simple queue is that even if there is a free memory space available in the
simple queue we cannot use that free memory space to insert element. Circular Queue is
designed to overcome the limitation of Simple Queue.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#define MAX 5
Char q[MAX],item;
int f=0,r=-1,count=0;
void insert();
void delete();
void display();
main()
{
int ch;
while(1)
{
printf("1.insert 2.delete 3.display 4.exit \n");
printf("enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:getchar();insert();
break;
case 2:delete();
break;
case 3:display();
break;
case 4:exit(0);
default :printf("Invalid choice\n");
break;
}
}
}
void insert()
{
if(count==MAX)
printf("queue overflow\n");
else
{
printf("enter the item to be inserted\n");
scanf("%c",&item );
r=(r+1)%MAX;
q[r]=item;
count++;
}
}
void delete()
{
if(count==0)
printf("queue underflow\n");
else
{
printf("deleted item is %c\n",q[f]);
f=(f+1)%MAX;
count--;
}
}
void display()
{
int j=f,i;
if(count==0)
printf("queue is empty\n");
else
{
printf("contents of circular queue\n");
for(i=1;i<=count;i++)
{
printf("%c\t",q[j]);
j=(j+1)%MAX;
}
printf("total number of items=%d\n",count);
}
}
Output
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the item to be inserted: A
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the item to be inserted: B
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the item to be inserted: C
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the item to be inserted: D
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 3
Contents of Queue is:
ABCD
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the character / item to be inserted: F
Queue is Full
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 2
Deleted item is: A
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 2
Deleted item is: B
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 3
Contents of Queue is:
CD
1. Insert 2. Delete 3. Display 4. Exit
Enter the choice: 1
Enter the item to be inserted: K
1. Insert 2. Delete
Enter the choice: 3
Program outcome:
Identify the applications of circular queue.
Implement insert and delete operations on circular queue.
Viva Questions:
What is a queue ?what are applications of queue?
What is Circular Queue? What is the difference between a Stack and a Queue?
PROGRAM 7
Design, Develop and Implement a menu driven Program in C for the
following operations on Singly Linked List (SLL) of Student Data with the
fields: USN, Name, Branch, 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 and Deletion at End of SLL
d Perform Insertion and Deletion at Front of SLL
e Demonstrate how this SLL can be used as STACKandQUEUE
f Exit
Program objective:
Understand the Singly Linked List (SLL) data structures.
Understand the methodology to insert and delete the element at the frontof
SLL.
Understand the methodology to insert and delete the element at theendof
SLL.
Get the knowledge of how SLL and be used as both stack and queue.
Algorithm
Step 1: declare structure of node createemptylist
head->null
Step2: Insert at front end
head<-null
returntemp
if list is empty
temp->link=head
return head
Step 3:Insert at rear end
head=null
returntemp
if list is empty
cur->head
while(cur!=null)
cur=cur->link
cur->link=temp;
return head
THEORY
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.
In any single linked list, the individual element is called as "Node". Every "Node" contains two
fields, data and next. The data field is used to store actual value of that node and next field is
used to store the address of the next node in the sequence.
They are a dynamic in nature which allocates the memory when required.
Insertion and deletion operations can be easilyimplemented.
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.
Drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting fromthe
first node. So we cannot do binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void create();
void insert_front();
void insert_rear();
void display();
void delete_front();
void delete_rear();
int count=0;
struct node{
char usn[20],name[50],branch[10];
int sem;
unsigned long long int phno;
struct node *link;
};
struct node *first=NULL,*last=NULL,*temp=NULL,*p;
void main()
{
int ch,n,i;
while(1)
{
printf("1.create SLL 2.insert at front 3.insert at rear 4.display 5.delete at front 6.delete at
rear 7.exit\n");
printf("enter choice\n");
scanf("%d",&ch);
switch(ch)
{
DEPT OF CSE, ATMECE, MYSURU Page 51
DATA STRUCTURES LABORATORY 18CSL38
case 1:printf("enter the no.of students\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
insert_front();
break;
case 2:insert_front();
break;
case 3:insert_rear();break;
case 4:display();break;
case 5:delete_front();break;
case 6:delete_rear();break;
case 7:exit(0);
default:printf("invalid choice\n");break;
}
}
}
void create()
{
char usn[20],name[50],branch[10];
int sem;
unsigned long long int phno;
temp=(struct node*)malloc(sizeof(struct node));
printf("enter usn,name,branch,sem,phno\n");
scanf("%s%s%s%d%llu",usn,name,branch,&sem,&phno);
strcpy(temp->usn,usn);
strcpy(temp->name,name);
strcpy(temp->branch,branch);
temp->sem=sem;
temp->phno=phno;
count++;
DEPT OF CSE, ATMECE, MYSURU Page 52
DATA STRUCTURES LABORATORY 18CSL38
}
void insert_front()
{
if(first==NULL)
{
create();
temp->link=NULL;
first=temp;
last=temp;
}
else
{
create();
temp->link=first;
first=temp;
}
}
void insert_rear()
{
if(first==NULL)
{
create();
temp->link=NULL;
first=temp;
last=temp;
}
else
{
create();
Output
MENU-
Enter choice :
2
List empty to display
MENU-
Enter choice :1
Enter no of students :
2
MENU-
Enter choice :
2
MENU-
Enter choice :
2
7 - exit
MENU-
Enter choice :
2
MENU-
Enter choice :
4
4ad16cs011 bharath cs 3 9912698467
MENU-
Enter choice :
2
MENU-
1 create a SLL of n emp
2 - Display frombeginning
3 - Insert at end
4 - delete at end
5 - Insert at beg
6 - delete at beg
7 - exit
Enter choice :
6
4ad16cs033 jayakumar cs 3 8903478345
MENU-
Enter choice :
2
MENU-
Enter choice :
8
wrong choice
MENU-
Enter choice :
7
Program outcome :
Implement Singly Linked List.
Implement insertion at the front and end of SLL.
Implement deletion at the front and end of SLL.
Identify the applications of SLL.
Familiarized how SLL can be used as both stack and queue.
Viva Questions :
What is a Linked List and What are its types? What is a node?
What are the parts of a linked list? What are the advantages of linked list?
Mention what is traversal in linked lists?
PROGRAM 8
Design, Develop and Implement 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
Program objective:
Understand the Doubly Linked List (DLL) data structures.
Understand the methodology to insert and delete the element at the frontof
DLL.
Understand the methodology to insert and delete the element at the endof
DLL.
Get the knowledge of how DLL and be used as double ended queue.
Algorithm
Insertion at front end of list.
Step 1: Allocate memory for temp node and assign values to node
Step2: if list is empty, temp is attached to list directly
head=null
returntemp
if list is not empty
temp->rlink=head
head->llink=temp
return head
return head;
Step 2: Traverse the cur node upto end of list before updating current pointer save
the
Address to prev pointer.
While(cur->rlink!=null)
{
prev=cur;
cur=cur->rlink;
}
prev->rlink=null;
cur->llink=null;
free(cur);
THEORY
In computer science, a doubly linked list is a linked data structure that consists of a set
of sequentially linked records called nodes.
Each node contains two fields, called links, that are references to the previous and to
the next node in the sequence of nodes. The beginning and ending nodes' previous and
next links, respectively, point to some kind of terminator, typically a sentinel node or
null, to facilitate traversal of the list. If there is only one sentinel node, then the list is
circularly linked via the sentinel node. It can be conceptualized as two singly linked
lists formed from the same data items, but in opposite sequential orders.
A doubly linked list whose nodes contain three fields: an integer value, the link to the
next node, and the link to the previous node.
The two node links allow traversal of the list in either direction. While adding or
removing a node in a doubly linked list requires changing more links than the same
operations on a singly linked list, the operations are simpler and potentially more
efficient (for nodes other than first nodes) because there is no need to keep track of the
previous node during traversal or no need to traverse the list to find the previous node,
so that its link can be modified.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void create();
void insert_front();
void insert_rear();
void display();
void delete_front();
void delete_rear();
int count=0;
struct node
{
int ssn;
char name[50],dept[20],desg[20];
float sal;
unsigned long long int phno;
struct node *llink,*rlink;
};
struct node *first=NULL,*last=NULL,*temp;
main()
{
int ch,n,i;
while(1)
{
printf("1.create\n 2.insert_front\n 3.insert_rear\n 4.display\n 5.delete_front\n 6.delete_rear\n
7.exit\n");
printf("enter choice\n");
Output
MENU-
Enter choice :
2
List empty to display
MENU-
Enter choice :
1
Enter no of employees :
2
Enter ssn,name,department, designation, salary and phno ofemployee :
120 harsha cs instructor 14000 9912378956
MENU-
Enter choice :
2
MENU-
MENU-
Enter choice :
2
Enter choice :
5
MENU-
Enter choice :
2
MENU-
MENU-
Enter choice :
2
MENU-
Enter choice :
6
MENU-
Enter choice :
2
MENU-
Enter choice :
7
$
Program outcome:
Implement Doubly Linked List.
Implement insertion at the front and end of DLL.
Implement deletion at the front and end of DLL.
Identify the applications of DLL.
Familiarized how DLL can be used as double ended queue.
Viva Questions:
What are doubly linked lists?
What is the difference between singly and doubly linked lists?
What are the advantages of double linked list over single linked list?
PROGRAM 9
Design, Develop and Implement a Program in C for the following operations
on Singly Circular Linked List (SCLL) with header nodes
a Represent and Evaluate a Polynomial P(x,y,z) = 6x2y2z-4yz5+3x3yz+2xy5z-
2xyz3
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)
Program objective: .
Understand the working of Singly Circular Linked List (SCLL).
Understand the use of header nodes.
Understand the methodology to evaluate polynomial usingSCLL.
Understand the methodology to add twopolynomialusingSCLL.
Algorithm:
Evaluate a Polynomial
Step1: allocate memory for newly created node assign values to that node
Step 2: attach newly created node to list in circular fashion.
Step3: Evaluate each node information up to header node
THEORY
Circular Linked List:
In the circular linked list the last node of the list contains the address of the first node
and forms a circular chain.
Circular Linked List is a variation of Linked list in which the first element points to the
last element and the last element points to the first element. Both Singly Linked List and
Doubly Linked List can be made into a circular linked list.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct node
{
int co,ex,ey,ez;
struct node *link;
};
typedef struct node NODE;
NODE *createnode(int,int,int,int);
NODE *attachnode(NODE*,NODE*);
NODE *readpoly();
void display(NODE*);
void evaluate(NODE*);
NODE *addpoly(NODE*,NODE*,NODE*);
temp=(NODE*)malloc(sizeof(NODE));
temp->co=co;
temp->ex=ex;
temp->ey=ey;
temp->ez=ez;
temp->link=NULL;
return temp;
}
head->link=head;
printf("enter the number of terms\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("term %d\n",i+1);
printf("enter the coefficient\n");
scanf("%d",&co);
printf("enter exponent values of x,yand z\n");
scanf("%d%d%d",&ex,&ey,&ez);
temp=createnode(co,ex,ey,ez);
head=attachnode(temp,head);
}
return head;
}
while(cur!=poly)
{
printf("%dx^%dy^%dz^%d+",cur->co,cur->ex,cur->ey,cur->ez);
cur=cur->link;
}
printf("\n");
}
res+=cur->co*pow(x,cur->ex)*pow(y,cur->ey)*pow(z,cur->ez);
cur=cur->link;
}
printf("result=%d\n",res);
}
b=b->link;
break;
case 1:temp=createnode(a->co, a->ex,a->ey,a->ez);
poly=attachnode(temp,poly);
a=a->link;
break;
case-1:temp=createnode(b->co,b->ex,b->ey,b->ez);
poly=attachnode(temp,poly);
b=b->link;
break;
}
}
while(a!=p1)
{
temp=createnode(a->co,a->ex,a->ey,a->ez);
poly=attachnode(temp,poly);
a=a->link;
}
while(b!=p2)
{ temp=createnode(b->co,b->ex,b->ey,b->ez);
poly=attachnode(temp,poly);
b=b->link;
}
return poly;
}
main()
{
int ch;
NODE *p1,*p2,*p3;
p3=(NODE*)malloc(sizeof(NODE));
p3->link=p3;
while(1)
{
printf("1.represent and evaluate 2.add two polynomial 3.exit\n");
printf("enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("enter a polynomial\n");
p1=readpoly();
display(p1);
evaluate(p1);
break;
case 2:printf("enter polynomial 1\n");
p1=readpoly();
display(p1);
printf(" enter polynomial 2\n");
p2=readpoly();
display(p2);
p3=addpoly(p1,p2,p3);
printf("the resultant polynomial is\n");
display(p3);
break;
case 3:exit(0);
default:printf("invalid choice\n");
break;
}
}}
Output
<< MENU >>
Polynomial Operations : 1.Add 2.Evaluate
3.Exit
Enter your choice==>1
Enter no of terms of polynomial==>3
Enter coef& expo==>
4
3
Enter coef& expo==> 22
Enter coef& expo==> 51
The polynomial is==>5x^(1) + 2x^(2) + 4x^(3)
Enter no of terms of polynomial==>3
Enter coef& expo==> 4 1
Enter coef& expo==>
3
2
Enter coef& expo==> 5 3
The polynomial is==>4x^(1) + 3x^(2) + 5x^(3)
Addition of polynomial==>
The polynomial is==>9x^(1) + 5x^(2) + 9x^(3)
Enter your choice==>2
Enter no of terms of polynomial==>3
Enter coef& expo==>
3
1
Program outcome :
Implement Singly Circular Linked List (SCLL) using header node.
Identify the application of SCLL.
Familiarized withthe methodology ofpolynomial evaluation andpolynomial
addition using SCLL.
Viva Questions:
What is circular linked list.?
What are Advantages and Disadvantages of Circular Linked List?
PROGRAM 10
Design, Develop and Implement 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 In-order, Preorder and PostOrder
C Searchthe BST for a givenelement (KEY) and reportthe appropriate
message
D Delete anelement (ELEM) from BST
E Exit
Program objective:
Understand the concept of Binary Search Tree (BST).
Understand the different traversal method on BST.
Get to know the methodology of searching a key element in BST.
Understand the methodology of deleting an element from BST.
Algorithm:
Preorder Traversal
Step 1: Display root information
Step2: Traverse left sub tree in preorder
Step 3: Traverse right sub tree in preorder
In order Traversal
Step 1: Traverse the left sub tree in order
Step 2: Display root information
Step3: Traverse right sub tree in order
THEORY
A binary search tree (BST) is a tree in which all nodes follows the below mentioned properties
The left sub-tree of a node has key less than or equalto its parent node’s V key.
The right sub-tree of a node has key greater than or equal to its parent node'skey.
Thus, a binary search tree (BST) divides all its sub-trees into two segments; left sub-tree and
right sub-tree and can be defined as
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
typedef struct bst
{
int data;
struct bst *rchild,*lchild;
}node;
node* getnode();
void insert(node*,node*);
void inorder(node*);
void preorder(node*);
void postorder(node*);
int search(node*,int);
int n;
node* getnode()
{
node *temp;
temp=(node*)malloc(sizeof(node));
temp->lchild=NULL;
temp->rchild=NULL;
return temp;
}
void main()
{
int ch;
int key,ans=1;
node *newnode,*root,*temp,*parent;
root=NULL;
while(1)
{
printf("1.create 2.search 3.travers 4.exit\n");
printf("enter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:while(ans==1)
{
newnode=getnode();
printf("enter the element\n");
scanf("%d",&newnode->data);
if(root==NULL)
root=newnode;
else
insert(root,newnode);
printf("want to continue[0/1]\n");
scanf("%d",&ans);
}
break;
case 2:printf("enter the element to search\n");
scanf("%d",&key);
search(root,key);
if(n==1)
printf("search successful\n");
else
printf("search unsuccessful\n");
break;
case 3:if(root==NULL)
printf("tree is empty\n");
else
{
printf("\n inorder traversal\n");
inorder(root);
printf("\n postorder traversal\n");
postorder(root);
printf("\n preorder traversal\n");
preorder(root);
}
break;
case 4:exit(0);break;
default :printf("wrong choice\n");
break;
}
}
}
void insert(node *root,node *newnode)
{
if(root->data<newnode->data)
{
if(root->rchild==NULL)
root->rchild==newnode;
else
insert(root->rchild,newnode);
}
else
{
if(root->lchild==NULL)
root->lchild=newnode;
else
insert(root->lchild,newnode);
}
}
void inorder(node *ptr)
{
if(ptr!=NULL)
{
inorder(ptr->lchild);
printf("%d\t",ptr->data);
inorder(ptr->rchild);
}
}
void preorder(node*ptr)
{
if(ptr!=NULL)
{
printf("%d\t",ptr->data);
preorder(ptr->lchild);
preorder(ptr->rchild);
}
}
void postorder(node *ptr)
{
if(ptr!=NULL)
{
postorder(ptr->lchild);
postorder(ptr->rchild);
printf("%d\t",ptr->data);
}
}
int search(node*root,int key)
{
node *temp;
temp=root;
if(root!=NULL)
{
if(temp->data==key)
n=1;
else if (key>temp->data)
search(temp->rchild,key);
else
search(temp->lchild,key);
}
else n=0;
return n;
}
Output
program for binary search tree
1.Create
2. Search
3. RecursiveTraversals
4.Exit
Enter your Choice= 1
Enter the element=15
Want to entermoreelements?(1/0)1
Enter the element=25
Want to entermoreelements?(1/0)1
Enter the element=35
Want to entermoreelements?(1/0)1
Enter the element=45
Want to entermoreelements?(1/0)1
Enter the element=5
Want to entermoreelements?(1/0)1
Enter the element=7
Want to enter more elements?(1/0)0
1.Create
2. Search
3. RecursiveTraversals
4.Exit
Enter your choice=2
Enter elements to be searched=7
The 7 element is present
parent of node 7 is 5
1.Create
2. Search
3. RecursiveTraversals
4.Exit
Enter your choice=2
Enter elements to be searched=88
the 88 element is not present
1.Create
2.Search
3.Recursive Traversals
4.Exit
Enter your choice=3
The inorder display =5 7 15 25 35 45
The preorder display=15 5 7 25 35 45
The postorder display=7 5 45 35 25 15
1.Create
2. Search
3. RecursiveTraversals
4.Exit
Enter your choice=4
Program outcome:
Implement Binary Search Tree (BST).
Implement the different traversal methodology on BST.
Familiarized with the methodology to search a key element in BST.
Implement the methodology to delete an element from BST.
Identify the applications of BST
Viva Questions:
What are binary trees?
Explain Binary Search Tree
How to check if a given Binary Tree is BST or not?
What is the minimum number of nodes that a binary tree can have?
What are the different types of traversing?
Define pre-order traversal?
Define post-order traversal?
Define in -order traversal?
PROGRAM 11
Design, develop and implement 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 ina digraph
using BFS method
c Check whether a given graph is connected or notusingDFS
Method.
Program objective:
Understand the concept of trees and adjacency matrix.
Understand the concept of connected graph.
Understand the Breath First Search(BFS) and Depth First Search(DFS)
traversal methodologies.
Algorithm:
THEORY
BFS first visits all the vertices that are adjacent to a starting vertex. Every time it adds the
adjacent vertex to a queue array q. On each successive iteration of the algorithm, the next
vertex on the queue is examined to see if there are any unvisited vertices adjacent to it which
can be added to the queue. Whenever a new vertex is taken from the queue, it is marked as a
visited node in the visited array.
Applications of BFS:
To check connectivity of a graph (number of times queue becomes emptytellsthe
number of components in thegraph)
To check if a graph is acyclic. (no cross edges indicates no cycle)
To find minimum edge path in a graph
Depth first search is a graph algorithm required for processing vertices or edges of a
graph in a systematic fashion. Depth first search starts visiting vertices of a graph at an
arbitrary vertex by marking it as having been visited. On each iteration, the algorithm proceeds
to an unvisited vertex that is adjacent to one it is currently in.
The algorithm backs up one edge to the vertex it came from and tries to continue
visiting unvisited vertices from there. The algorithm eventually halts after backing up to
starting vertex, with the latter being dead end. By then, all vertices in the same connected
component as the starting vertex have been visited. If unvisited vertices still remain, the depth
first search must be restarted at any one of them.
Here we use a STACK to trace the depth first search. We push a vertex onto the stack
when the vertex is reached for the first time, and we pop a vertex off the stack when it
becomes a dead end.
Applications of DFS:
The two orderings are advantageous for various applications liketopologicalsorting,
etc.
To check connectivity ofa graph (number oftimes stack becomes emptytells the
number of components in thegraph)
To check if a graph is acyclic. (no back edges indicates no cycle)
To find articulation point in a graph
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int n,a[10][10],i,j,source,s[10],choice,count;
void bfs(int n,int a[10][10],int source,int s[])
{
int q[10],u;
int front=1,rear=1;
s[source]=1;
q[rear]=source;
while(front<=rear)
{
u=q[front];
front=front+1;
for(i=1;i<=n;i++)
if(a[u][i]==1 &&s[i]==0)
{
rear=rear+1;
q[rear]=i;
s[i]=1;
}
}
}
void dfs(int n,int a[10][10],int source,int s[])
{
s[source]=1;
for(i=1;i<=n;i++)
if(a[source][i]==1 && s[i]==0)
dfs(n,a,i,s);
}
int main()
{
printf("Enter the number of nodes : \n");
scanf("%d",&n);
printf("\n Enter the adjacency matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
while(1)
{
}
}
}
Output1
1. BFS
2. DFS
3. Exit
1. BFS
2. DFS
3. Exit
1.BFS
2. DFS
3. Exit
enter your choice
3
Output2
1. BFS
2. DFS
3. Exit
1. BFS
2. DFS
3. Exit
1.BFS
2. DFS
3. Exit
Output3
1. BFS
2. DFS
3. Exit
1. BFS
2. DFS
3. Exit
1.BFS
2. DFS
3. Exit
Program outcomes:
Create graph using adjacency matrix.
Implement Breadth First Search (BFS) and Depth First Search(DFS).
Familiarized with connected graph.
Identify the applications of graphs.
Viva Questions:
What is a graph?
What is a tree?
What is BFS and DFS?
Which data structures are used for BFS and DFS of a graph?
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 mmemory 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.
Design and 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.
Program objective:
Understand what is hashing and hashing function.
Understand the concept of linear probing.
Understand the concept ofcollision detectionand avoidance usinglinear
probing.
Algorithm:
Step 1: Start
Step 2: Initialize all memory locations with some values to identity as space
a[i]=-1
Step 3: Read Employee key value .calculate hash key using remainder method
hk<-key%100
Step 4: Inserting Employee record using key
Inserting hash dull function
If(count=m)
If space is available for that key
If(H[k]==-1)
H[hk] <-key
If collision occurs, it can be solved using linear probing method.
Checking free space from key to end
for(i=hk+1;i<m;i++)
Checking free space from beginning to key value.
for(i=0;i<hk&& flag==0;i++)
Step 5: Display all memory location with index and employee key
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
void display(int a[MAX]);
int create(int num);
void linearprob(int a [MAX],int key,int num);
void main()
{
int a[MAX],i,num,key,ans=1;
printf("collission handling by linear probing\n");
for(i=0;i<MAX;i++)
a[i]= -1;
do
{
printf("enter the data\n");
scanf("%4d",&num);
key=create(num);
linearprob(a,key,num);
printf("do yuou want to continue[1/0]\n");
scanf("%d",&ans);
}while(ans);
display(a);
}
int create(int num)
{
int key;
key=num%100;
return key;
}
else
{
for(i=0;i<MAX;i++)
{
if(a[i]!=-1)
{
printf("%d\t %d\n",i,a[i]);
continue;
}
}
}
}
Output
collision handling by linear probing :
Enter the data1234
Do you wish to continue ? (1/0)1
Enter the data2548
Do you wish to continue ? (1/0)1
Enter the data3256
Do you wish to continue ? (1/0)1
Enter the data1299
Do you wish to continue ? (1/0)1
Enter the data1298
Do you wish to continue ? (1/0)1
Enter the data1398
Collision Detected...!!!
Collision avoided successfully using LINEAR PROBING
Do you wish to continue ? (1/0) 0
1.Display ALL
2.Filtered Display
the hash table is
0 1398
341234
482548
563256
981298
991299
Program outcome:
Implement hashing function.
Implement linear probing.
Familiarized the concept ofcollusion detectionand avoidance and detection
using linear probing.
Identify the application of hashing and linear probing.
Viva Questions:
What is Hashing?
What is Linear Probing?