Sie sind auf Seite 1von 80

Data Structures Laboratory Manual

LAB PROGRAM 1:

Design, Develop and Implement a menu driven program in C for the following Array
operations
a. Creating 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.

ABOUT THE EXPERIMENT:


An Array is a collection of similar /same elements. In this experiment the array can be
represented as one / single dimensional elements. Menu driven program in c - language to
perform various array operations are implemented with the help of user defined functions as
followings; a. create() b. display() c. insert() d. del() e. exit()

ALGORITHM:
Step 1: Start.
Step 2: Read N value.
Step 3: Read Array of N integer elements
Step 4: Print array of N integer elements.
Step 5: Insert an element at given valid position in an array
Step 6: Delete an element at given valid position from an array.
Step 7: Stop.

PROGRAM CODE :

#include<stdio.h>
void create();
void display();
void insert_pos();
void del_pos();
int n,a[150],count;
int main()
{
int ch;
while(1)
{
printf("\nARRAY OPERATIONS- MENU\n");
printf("1. CREATE AN ARRAY\n");
printf("2. DISPLAY ARRAY ELEMENTS\n");
printf("3. INSERT AN ELEMENT AT A POSITION\n");
printf("4. DELETE AN ELEMENT FROM A POSTION\n");
printf("5. EXIT\n");
printf("ENTER YOUR CHOICE\n");

Dept. of CS&E , JSSATEB Page 1


Data Structures Laboratory Manual

scanf("%d",&ch);
switch(ch)
{
case 1: if(count==0||n==0)
create();
else
printf("ARRAY ALREADY CREATED\n");
break;
case 2: if(count==0||n<0)
printf("array not created, create the array \n");
else
display();
break;
case 3: if(count==0||n<0)
printf("array not created, create the array \n");
else
insert_pos();
break;
case 4: if(count==0||n<0)
printf("array not created,create array \n");
else
del_pos();
break;
case 5: return(0);
default: printf("invalid choice\n");
}
}
}
void create()
{
int i;
printf("enter the number of elements\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
count++;
}
void display()
{
int i;
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void insert_pos()

Dept. of CS&E , JSSATEB Page 2


Data Structures Laboratory Manual

{
int i,pos,item;
printf("enter the position and value of the item to be inserted in the array\n");
scanf("%d%d",&pos,&item);
if(pos<0||pos>n+1)
{
printf("invalid position\n");
}
else
{
pos--;
for(i=n-1;i>=pos;i--)
a[i+1]=a[i];
a[pos]=item;
n++;
}
}
void del_pos()
{
int i,pos,val;
printf("enter the position of the element to be deleted\n");
scanf("%d",&pos);
if(pos<0||pos>n)
{
printf("invalid position\n");
}
else
{
val=a[--pos];
for(i=pos;i<n-1;i++)
a[i]=a[i+1];
n--;
printf("the element deleted is %d\n",val);
}
}

OUTPUT :

Array operations:
1.create
2. display
3. insert at a position
4. delete from a given position
5. Exit
Enter your choice:
1

Dept. of CS&E , JSSATEB Page 3


Data Structures Laboratory Manual

Enter the elements


1
3
4
5
6
Array operations:
1.create
2. display
3. insert at a position
4. delete from a given position
5. Exit
Enter your choice:
2
The elements are
1
3
4
5
6
Array operations:
1.create
2. display
3. insert at a position
4. delete from a given position
5. Exit
Enter your choice:
3
Enter the position and element to be inserted:
22
Array operations:
1.create
2. display
3. insert at a position
4. delete from a given position
5. Exit
Enter your choice:
2
The elements are
1
2
3
4
5
6
Array operations:

Dept. of CS&E , JSSATEB Page 4


Data Structures Laboratory Manual

1.create
2. display
3. insert at a position
4. delete from a given position
5. Exit
Enter your choice:
4
Enter the position of the member to be deleted
6
The element deleted is 6
Array operations:
1.create
2. display
3. insert at a position
4. delete from a given position
5. Exit
Enter your choice:
2
The elements are
1
2
3
4
5
Array operations:
1.create
2. display
3. insert at a position
4. delete from a given position
5. Exit
Enter your choice:
6
Invalid choice
Array operations:
1.create
2. display
3. insert at a position
4. delete from a given position
5. Exit
Enter your choice:
5

Dept. of CS&E , JSSATEB Page 5


Data Structures Laboratory Manual

LAB 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.
Repost 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.

ABOUT THE EXPERIMENT:

Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus
a null-terminated string contains the characters that comprise the string followed by a null. The
following declaration and initialization create a string consisting of the word "Hello".
To hold the null character at the end of the array, the size of the character array containing the
string is one more than the number of characters in the word "Hello." char greeting[6] = {'H', 'e',
'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows:
char greeting[] = "Hello";
C language supports a wide range of built-in functions that manipulate null-terminated strings as
follows:
strcpy(s1, s2); Copies string s2 into string s1.
strcat(s1, s2); Concatenates string s2 onto the end of string s1.
strlen(s1); Returns the length of string s1.
strcmp(s1, s2);Returns 0 if s1 and s2 are the same; less than 0 if s1s2.
strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.

ALGORITHM:
Step 1: Start.
Step 2: Read main string STR, pattern string PAT and replace string REP.
Step 3: Search / find the pattern string PAT in the main string STR.
Step 4: if PAT is found then replace all occurrences of PAT in main string STR with REP string.
Step 5: if PAT is not found give a suitable error message.
Step 6: Stop

PROGRAM CODE

#include<stdio.h>
#include<string.h>
int find_match(char str[10]],char pat[100],char rep[100],char ans[100]);
void main()
{

Dept. of CS&E , JSSATEB Page 6


Data Structures Laboratory Manual

char str[100],pat[100],rep[100],ans[100];
int flag;
printf("enter the main string\n");
gets(str);
printf("enter the pattern string to be searched\n");
gets(pat);
printf("enter the replacement string\n");
gets(rep);
flag= find_match(str,pat,rep,ans);
if(flag)
{
printf("\n pattern found\n");
printf("\n the string after replacement is %s",ans);
}
else
printf("\n pattern not found\n");
}
int find_match(char str[100],char pat[100],char rep[100],char ans[100])
{
int i,j,m,c,flag,k;
i=j=m=c=flag=0;
while(str[c]!='\0')
{
if(str[m]==pat[i])
{
i++;
m++;
if(pat[i]=='\0')
{
flag=1;
for(k=0;rep[k]!='\0';k++,j++)
ans[j] =rep[k];
i=0;c=m;
}
}
else
{
ans[j]=str[c];
j++;
c++;
m=c;
i=0;
}
}
ans[j]='\0';
return flag;

Dept. of CS&E , JSSATEB Page 7


Data Structures Laboratory Manual

OUTPUT :

1)
Enter the main string
Good morning how are you this morning
Enter the Pattern string
morning
Enter the replacement string
afternoon
The string after replacement is good afternoon how are you this afternoon

2)
Enter the main string
Hello how are you
Enter the Pattern string
not
Enter the replacement string
how
pattern not found

Dept. of CS&E , JSSATEB Page 8


Data Structures Laboratory Manual

LAB 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 on to stack
b. Pop an element from stack
c. Demonstrate how stack can be used to check palindrome.
d. Demonstrate Overflow and Underflow situations on stack.
e. Display the status of stack.
f. Exit.
Support the program with appropriate functions for each of the above operations.

ABOUT THE EXPERIMENT:

A stack is an abstract data type (ADT), commonly used in most programming languages. It is
named stack as it behaves like a real-world stack.
A real-world stack allows operations at one end only. For example, we can place or remove a
card or plate from top of the stack only. Likewise, Stack ADT allows all data operations at one
end only. At any given time, we can only access the top element of a stack. This feature makes it
LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed
(inserted or added) last is accessed first. In stack terminology, insertion operation is called PUSH
operation and removal operation is called POP operation.

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.
Basic Operations:
push() - pushing (storing) an element on the stack.
pop() -removing (accessing) an element from the stack

To use a stack efficiently we need to check status of stack as well. For the same purpose, the
following functionality is added to stacks;
peek() − get the top data element of the stack, without removing it.
isFull() − check if stack is full.
isEmpty() − check if stack is empty.

ALGORITHM:

Step 1: Start.
Step 2: Initialize stack size MAX and top of stack -1.
Step 3: Push integer element on to stack and display the contents of the stack. if stack is full give
a message as ‘Stack is Overflow’.
Step 3: Pop element from stack along with display the stack contents. if stack is empty give a
message as ‘Stack is Underflow’.
Step 4: Check whether the stack contents are Palindrome or not.
Step 5: Stop.

Dept. of CS&E , JSSATEB Page 9


Data Structures Laboratory Manual

PROGRAM CODE

#include<stdio.h>
#include<process.h>
#define smax 5
void push();
void pop();
void palin();
void display();
int top=-1, stk[smax];
void main()
{
int ch,d;
while(1)
{
printf("\nSTACK MENU\n");
printf("1. PUSH\n");
printf("2. POP\n");
printf("3. PALINDROME CHECK\n");
printf("4. DISPLAY\n");
printf("5. EXIT\n");
printf("ENTER YOUR CHOICE\n");
scanf("%d",&ch);
switch(ch)
{
case 1: push();
break;
case 2: pop();
break;
case 3: palin();
break;
case 4: display();
break;
case 5: exit(0);
default: printf("INVALID CHOICE\n");
}
} }
void push()
{
int item;
if(top==smax-1)
printf("\n STACK FULL\n");
else
{
printf("enter the item to be inserted\n");

Dept. of CS&E , JSSATEB Page 10


Data Structures Laboratory Manual

scanf("%d",&item);
stk[++top]=item;
}
}
void pop()
{
int d;
if(top==-1)
printf("\n STACK EMPTY\n");
else
{
d=stk[top];
top--;
printf("the deleted element is %d\n",d);
}
}
void display()
{
int i;
if(top==-1)
printf("\n STACK EMPTY\n");
else
{
printf("\n CONTENTS OF STACK ARE\n");
for(i=top;i>=0;i--)
printf("%d\n",stk[i]);
}
}
void palin()
{
int j=0, flag=1;
int rev[smax],i;
if(top==-1||top==0)
{
printf("\n PALINDROME CANNOT BE CHECKED\n");
return;
}
else
{
for(i=top;i>=0;i--,j++)
rev[j]=stk[i];
for(i=0;i<=top;i++)
{
if(rev[i]!=stk[i])
{
flag=0;

Dept. of CS&E , JSSATEB Page 11


Data Structures Laboratory Manual

break;
}
} }
if(flag)
printf("\n IT IS A PALINDROME\n");
else
printf("\n IT IS NOT A PALINDROME\n");
}

OUTPUT:

Stack menu
1.push
2.pop
3.palin
4.display
5 . exit
Enter your choice
1
Enter the element to be inserted
1
Stack menu
1.push
2.pop
3.palin
4.display
5.exit
Enter your choice
1
Enter the element to be inserted
2
Stack menu
1.push
2.pop
3.palin
4.display
5.exit
Enter your choice
1
Enter element to be inserted
2
Stack menu
1.push
2.pop
3.palin

Dept. of CS&E , JSSATEB Page 12


Data Structures Laboratory Manual

4.display
5.exit
Enter your choice
1
Enter the element to be inserted
1
Stack menu
1.push
2.pop
3.palin
4.display
5.exit
Enter your choice
1
Enter the element to be inserted
1
Stack menu
1.push
2.pop
3.palin
4.display
5.exit
Enter your choice
1
Enter the element to be inserted
1
Stack full
Stack menu
1.push
2.pop
3.palin
4.display
5.exit
Enter your choice
3
Not a palindrome
Stack menu
1.push
2.pop
3.palin
4.display
5.exit
Enter your choice
4
Stack elements
1

Dept. of CS&E , JSSATEB Page 13


Data Structures Laboratory Manual

1
2
2
1
Stack menu
1.push
2.pop
3.palin
4.display
5.exit
Enter your choice
2
The deleted element is 1
Stack menu
1.push
2.pop
3.palin
4.display
5.exit
Enter your choice
3
It is a palindrome
Stack menu
1.push
2.pop
3.palin
4.display
5.exit
Enter your choice
5

Dept. of CS&E , JSSATEB Page 14


Data Structures Laboratory Manual

LAB 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.

ABOUT THE EXPERIMENT:

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+

ALGORITHM:
Step 1: Start.
Step 2: Read an infix expression with parenthesis and without parenthesis.
Step 3: convert the infix expression to postfix expression.
Step 4: Stop

PROGRAM CODE

#include<stdio.h>
int stk_precedence(char); //function prototypes
int input_precedence(char );
char pop();
void push(char);
char postfix[50],infix[50],s[50];
int top=-1; //initially stack is empty
void main()
{
int i,j=0;
char ch,elem;
clrscr();
printf("enter a valid infix expression\n");
gets(infix);
push('#'); //insert '#' to mark the end of the stack
for(i=0;infix[i]!='\0';i++)
{
ch=infix[i]; //take each character
if(isalnum(ch)) //check if it is an operand
postfix[j++]=ch; //if yes copy the operand into postfix
expression

Dept. of CS&E , JSSATEB Page 15


Data Structures Laboratory Manual

else if(ch=='(')
push(ch);
else if(ch==')') /* if input symbol is ')' then pop the elements of the stack
and store it in postfix expression until u get '(' at the top*/
{
while( s[top]!='(')
postfix[j++]=pop();
elem=pop();
}
else /*if operator find the precedence of stack operator
and input symbol*/
{
while(stk_precedence(s[top])>=input_precedence(ch))
postfix[j++]=pop();
push(ch);
}
}
while(s[top]!='#') /*pop the contents of the stack and store in postfix
expression until end of the stack is reached*/
postfix[j++]=pop();
postfix[j]='\0';
printf("the post fix expression is %s\n",postfix);
}
/*function to give precedence to operators in the stack*/
int stk_precedence(char e)
{
switch(e)
{
case '+':
case '-': return(2);
case '*':
case '/':
case '%': return(4);
case '^': return(5);
case '(':
case'#': return(0);
}
}
/*function to give precedence to operators in the input symbol scanned */
int input_precedence(char e)
{
switch(e)
{
case '+':
case '-': return(1);
case '*':

Dept. of CS&E , JSSATEB Page 16


Data Structures Laboratory Manual

case '/':
case '%': return(3);
case '^': return(6);
case '(':
case'#': return(0);
}
}
/*function to push a character onto the stack*/
void push(char ele)
{
++top;
s[top]=ele;
}
/*function to pop a character from the stack*/
char pop()
{
char e;
e=s[top];
--top;
return e;
}

OUTPUT :

1. Enter the infix expression


X^Y^Z
Postfix expression is XYZ^^
2. Enter the infix expression
a+b*c+(d*e+f*) g
Postfix expression is abc*de*f+g*+
3. Enter the infix expression
2+3*6/2+2+3^2
Postfix expression is 236*2/+2+32^+
4. Enter the infix expression
a+b+c
Postfix expression is ab+c+

Dept. of CS&E , JSSATEB Page 17


Data Structures Laboratory Manual

LAB PROGRAM 5

5(a)
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.

ABOUT THE EXPERIMENT:


a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
Postfix/Suffix Expression: Operators are written after their operands.
b. Ex: XY+ In normal algebra we use the infix notation like a+b*
c. The corresponding postfix notation is abc*+
d. Example: Postfix String: 123*+4

ALGORITHM:
Step 1: Start.
Step 2: Read the postfix/suffix expression.
Step 3: Evaluate the postfix expression based on the precedence of the operator.
Step 4: Stop.

PROGRAM CODE

#include<stdio.h> //header files


#include<ctype.h>
#include<math.h>
#define max 20
void push(int e); //function prototypes
int pop();
int a[max],top=-1; //global declarations
void main()
{
char post[max],ch;
int i,op1,op2,result;
printf("program to evaluate post fix expression\n");
printf("enter the post fix expression\n");
scanf("%s",post);
for(i=0;post[i]!='\0';i++)
{
ch=post[i]; //take one symbol from the expression
if(isdigit(ch)) //check if it is an operand
push(ch-'0');
else //else if it is an operator
{ //pop 2 operands from the stack
op2=pop();

Dept. of CS&E , JSSATEB Page 18


Data Structures Laboratory Manual

op1=pop();
switch(ch) //perform the operation depending upon the operator
{
case '+': result=op1+op2;
break;
case '-': result=op1-op2;
break;
case '*': result=op1*op2;
break;
case '/' : result=op1/op2;
break;
case'^': result=pow(op1,op2);
break;
case '%': result = op1%op2;
break;
default: printf("invalid character\n");
}
push(result); //push the result on to the stack
}
}
printf("result of the above expression is %d",pop()); /*pop the final result from the
stack*/
}
/*function to push*/
void push(int e)
{
++top;
a[top]=e;
}
/*function to pop*/
int pop()
{
int ele;
ele=a[top];
--top;
return(ele);
}

OUTPUT :
Enter the valid postfix expression
63+5*23++
The result of expression is 50
Enter the valid postfix expression
874*+3-2*
The result of the expression is 66

Dept. of CS&E , JSSATEB Page 19


Data Structures Laboratory Manual

5(b)
Solving Tower of Hanoi problem with n disks.

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 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 smaller disk.
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 2 n - 1, where n is
the number of disks.

ALGORITHM:
Step 1: Start.
Step 2: Read N number of discs.
Step 3: Move all the discs from source to destination by using temp rod.
Step 4: Stop.

PROGRAM CODE:

#include<stdio.h>
int count=0;
void tower(int n, char s, char t, char d)
{
if(n==1)
{
printf("Move disc 1 from %c to %c\n", s, d);
count ++;
return;
}
tower(n-1, s, d, t);
printf("Move disc %d from %c to %c\n", n, s,d);
count ++;
tower(n-1, t, s, d);
}
void main()
{
int n;
printf("Enter the number of discs\n");
scanf("%d", &n);
tower(n, 'A','B','C');

Dept. of CS&E , JSSATEB Page 20


Data Structures Laboratory Manual

printf("Total number of moves =%d\n", count);


}

OUTPUT :

TOWER OF HANOI
Enter the number of discs 3
Move the disc 1 from A to C
Move the disc 2 from A to B
Move the disc 1 from C to B
Move the disc 3 from A to C
Move the disc 1 from B to A
Move the disc 2 from B to C
Move the disc 1 from A to C
Total number of moves is 7

Dept. of CS&E , JSSATEB Page 21


Data Structures Laboratory Manual

LAB 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

ABOUT THE EXPERIMENT:

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. Circular linked list fallow the First In
First Out principle. 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. Any position before front is also after rear.

ALGORITHM:

Step 1: Start.
Step 2: Initialize queue size to MAX
Step 3: Insert the elements into circular queue. If queue is full give a message as ‘queue is
overflow”
Step 4: Delete an element from the circular queue. If queue is empty give a message as ‘queue is
underflow’.
Step 5: Display the contents of the queue.
Step 6: Stop.

PROGRAM CODE :

#include<stdio.h>
#include<process.h>
#define smax 5
void insert();
void del();
void display();
int rear=-1,front=0,count;
char queue[smax];
void main()
{
int ch;

Dept. of CS&E , JSSATEB Page 22


Data Structures Laboratory Manual

while(1)
{
printf("\n CIRCULAR QUEUE IMPLEMENTATION\n");
printf("1. INSERT \n");
printf("2. DELETE \n");
printf("3. DISPLAY\n");
printf("4. EXIT\n");
printf("\n ENTER YOUR CHOICE\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert();
break;
case 2: del();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\n INVALID CHOICE\n");
}
}
}
void insert()
{
char item,ch;
if(count>=smax)
printf("\n QUEUE FULL\n");
else
{
ch=getchar();
printf("enter the item to be inserted\n");
scanf("%c",&item);
rear=(rear+1)%smax;
queue[rear]=item;
count++;
}
}
void del()
{
char d;
if(count<=0)
printf("\n QUEUE UNDER FLOW\n");
else
{
d=queue[front];
front=(front+1)%smax;

Dept. of CS&E , JSSATEB Page 23


Data Structures Laboratory Manual

printf("\n the deleted element is %c",d);


count--;
}
}
void display()
{
int i,j;
if(count<=0)
printf("\n QUEUE UNDER FLOW\n");
else
{
i=front;
for(j=1;j<=count;j++)
{
printf("%c\n",queue[i]);
i=(i+1)%smax;
}
}
}

OUTPUT :

Circular Queue Operations


1.Insert
2.Delete
3.Display
4.Exit
Enter the choice
2
Queue is empty
Circular Queue Operations
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice
1
Enter the item
b
Circular Queue Operations
1.Insert
2.Delete
3.Display
4.Exit

Dept. of CS&E , JSSATEB Page 24


Data Structures Laboratory Manual

Enter the choice


1
Enter the item
c
Circular Queue Operations
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice
1
Enter the item
d
Circular Queue Operations
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice
1
Enter the item
e
Circular Queue Operations
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice
1
Enter the item
f
Circular Queue Operations
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice
1
Queue is full
Circular Queue Operations
1.Insert
2.Delete
3.Display

Dept. of CS&E , JSSATEB Page 25


Data Structures Laboratory Manual

4.Exit
Enter the choice
3
The elements are
b
c
d
e
f
Circular Queue Operations
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice
2
Enter the position
1
Deleted element is b
Circular Queue Operations
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice
3
The elements are
c
d
e
f
Circular Queue Operations
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice
1
Enter the item
a
Circular Queue Operations
1.Insert
2.Delete
3.Display
Dept. of CS&E , JSSATEB Page 26
Data Structures Laboratory Manual

4.Exit
Enter the choice
3
The elements are
c
d
e
f
a
Circular Queue Operations
1.Insert
2.Delete
3.Display
4.Exit
Enter the choice
4

Dept. of CS&E , JSSATEB Page 27


Data Structures Laboratory Manual

LAB 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 STACK and QUEUE
f. Exit

ABOUT THE EXPERIMENT

Singly linked list is the most basic linked data structure. In this the elements can be placed
anywhere in the heap memory unlike array which uses contiguous locations. Nodes in a linked
list are linked together using a next field, which stores the address of the next node in the next
field of the previous node i.e. each node of the list refers to its successor and the last node
contains the NULL reference. It has a dynamic size, which can be determined only at run time.

Basic operations of a singly-linked list are:


1. Insert – Inserts a new element at the end of the list.
2. Delete – Deletes any node from the list.
3. Find – Finds any node in the list.
4. Print – Prints the list.

Algorithm:
The node of a linked list is a structure with fields data (which stored the value of the node) and
*next (which is a pointer of type node that stores the address of the next node).

Two nodes *start (which always points to the first node of the linked list) and *temp (which is
used to point to the last node of the linked list) are initialized. Initially temp = start and temp-
>next = NULL. Here, we take the first node as a dummy node. The first node does not contain
data, but it used because to avoid handling special cases in insert and delete functions.
Functions –

1. Insert – This function takes the start node and data to be inserted as arguments. New node is
inserted at the end so, iterate through the list till we encounter the last node. Then, allocate
memory for the new node and put data in it. Lastly, store the address in the next
field of the new node as NULL.

2. Delete - This function takes the start node (as pointer) and data to be deleted as arguments.
Firstly, go to the node for which the node next to it has to be deleted,

If that node points to NULL (i.e. pointer->next=NULL) then the element to be deleted
is not present in the list.

Dept. of CS&E , JSSATEB Page 28


Data Structures Laboratory Manual

Else, now pointer points to a node and the node next to it has to be removed, declare a
temporary node (temp) which points to the node which has to be removed. Store the address
of the node next to the temporary node in the next field of the node pointer (pointer->next
= temp->next). Thus, by breaking the link we removed the node which is next to the
pointer (which is also temp). Because we deleted the node, we no longer require the
memory used for it, free() will deallocate the memory.

3. Find - This function takes the start node (as pointer) and data value of the node (key) to be
found as arguments. First node is dummy node so, start with the second node. Iterate through the
entire linked list and search for the key.
Until next field of the pointer is equal to NULL, check if pointer->data = key. If it is then
the key is found else, move to the next node and search (pointer = pointer -> next). If key is not
found return 0, else return 1.

4. Print - function takes the start node (as pointer) as an argument. If pointer = NULL, then there
is no element in the list. Else, print the data value of the node (pointer->data) and move to the
next node by recursively calling the print function with pointer->next sent as an argument.

PROGRAM CODE :

#include<stdio.h>
#include<conio.h>
#include<process.h>
typedef struct node
{
char usn[20],name[20],branch[10],phno[10];
int sem;
struct node *link;
}NODE;
NODE *start= NULL;
int count_nodes();
void main_menu();
void create_list();
void insert_front();
void display();
void insert_end();
void del_front();
void del_end();
void stack();
void queue();
void main()
{
main_menu();
}

Dept. of CS&E , JSSATEB Page 29


Data Structures Laboratory Manual

void main_menu()
{
int ch;
clrscr();
while(1)
{
printf("\n SINGLY LINKED LIST IMLEMENTATION\n");
printf("\n 1. CREATE LIST\n");
printf("\n 2. INSERTION AND DELETION FROM FRONT(STACK)\n");
printf("\n 3. INSERTION AND DELETION FROM END(QUEUE)\n");
printf("\n 4. DISPLAY\n");
printf("\n 5. exit\n");
printf("\n ENTER YOUR CHOICE\n");
scanf("%d",&ch);
switch(ch)
{
case 1: create_list();
break;
case 2: stack();
break;
case 3: queue();
break;
case 4: display();
break;
case 5: exit(0);
default: printf("\n INVALID CHOICE\n");
}
}
}
void create_list()
{
//NODE *newnode=NULL;
int n,i;
printf("enter the number of nodes\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
/*newnode=(NODE*)malloc(sizeof(NODE));
printf("enter USN\n");
scanf("%s",newnode->usn);
printf("enter name and branch\n");
scanf("%s%s",newnode->name,newnode->branch);
printf("enter semester\n");
scanf("%d",&newnode->sem);
printf("enter phone number\n");
scanf("%s",newnode->phno);

Dept. of CS&E , JSSATEB Page 30


Data Structures Laboratory Manual

newnode->link=start;
start=newnode;*/
insert_front();
}
}
void display()
{
NODE*curptr=NULL;
if(start==NULL)
printf("\n LIST EMPTY\n");
else
{
curptr=start;
printf("\n USN\tNAME\tBRANCH\tSEM\tPHONENUMBER\n");
while(curptr!=NULL)
{
printf("%s\t%s\t%s\t%d\t%s\n",curptr->usn,curptr->name,curptr->branch,curptr-
>sem,curptr->phno);
curptr=curptr->link;
}
printf("\n NUMBER OF NODES= %d",count_nodes());
}
}
void stack()
{
int ch;
while(1)
{
printf("\n STACK IMPLEMENTATION\n");
printf("\n 1.insert front\n");
printf("\n 2. delete front\n");
printf("\n 3. display\n");
printf("\n 4. exit from stack menu\n");
printf("\n enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert_front();
break;
case 2: del_front();
break;
case 3: display();
break;
case 4: main_menu();
break;
default: printf("\n invalid choice\n");

Dept. of CS&E , JSSATEB Page 31


Data Structures Laboratory Manual

}
}
}
void insert_front()
{
NODE *newnode=NULL;
newnode=(NODE*)malloc(sizeof(NODE));
printf("enter USN\n");
scanf("%s",newnode->usn);
printf("enter name and branch\n");
scanf("%s%s",newnode->name,newnode->branch);
printf("enter semester\n");
scanf("%d",&newnode->sem);
printf("enter phone number\n");
scanf("%s",newnode->phno);
newnode->link=start;
start=newnode;
}
void del_front()
{
NODE* curptr=NULL;
if(start==NULL)
printf("\n LIST EMPTY\n");
else
{
curptr=start;
start=start->link;
printf("the deleted information is \n");
printf("\n USN\tNAME\tBRANCH\tSEM\tPHONENUMBER\n");
printf(" %s\t%s\t%s\t%d\t%s\n",curptr->usn,curptr->name,curptr-
>branch,curptr->sem,curptr->phno);
free(curptr);
}
}
int count_nodes()
{
NODE * curptr =NULL;
int ctr=0;
if(start==NULL)
return 0;
else
{
curptr=start;
while(curptr!=NULL)
{
ctr++;

Dept. of CS&E , JSSATEB Page 32


Data Structures Laboratory Manual

curptr=curptr->link;
}
}
return ctr;
}
void queue()
{
int ch;
while(1)
{
printf("\n QUEUE IMPLEMENTATION\n");
printf("\n 1.insert end\n");
printf("\n 2. delete end\n");
printf("\n 3. display\n");
printf("\n 4. exit from queue menu\n");
printf("\n enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert_end();
break;
case 2: del_end();
break;
case 3: display();
break;
case 4: main_menu();
break;
default: printf("\n invalid choice\n");
}
}
}
void insert_end()
{
NODE * curptr,*newnode=NULL;
newnode=(NODE*)malloc(sizeof(NODE));
printf("enter USN\n");
scanf("%s",newnode->usn);
printf("enter name and branch\n");
scanf("%s%s",newnode->name,newnode->branch);
printf("enter semester\n");
scanf("%d",&newnode->sem);
printf("enter phone number\n");
scanf("%s",newnode->phno);
if(start==NULL)
{
newnode->link=start;

Dept. of CS&E , JSSATEB Page 33


Data Structures Laboratory Manual

start=newnode;
}
else
{
curptr=start;
while(curptr->link !=NULL)
curptr=curptr->link;
newnode->link=NULL;
curptr->link=newnode;
}
}

void del_end()
{
NODE *curptr=NULL,*nextcur=NULL;
if(start==NULL)
printf("\n LIST EMPTY\n");
else if(start->link==NULL)
free(start);
else
{
curptr=start;
nextcur=curptr;
while(curptr->link!=NULL)
{
nextcur=curptr;
curptr=curptr->link;
}
nextcur->link=NULL;
free(curptr);
}
}

OUTPUT :

SINGLY LINKED LIST IMPLEMENTATION


1.Create
2.Stack operation
3.Queue operation
4.Deletion from end
5.Display
6.Exit
Enter your choice:
1
Enter the value of n:
3

Dept. of CS&E , JSSATEB Page 34


Data Structures Laboratory Manual

Enter the USN:


1JS15CS001
Enter the name and branch:
ABHI
CSE
Enter the semester and phone number:
3
9876543210
Enter the USN:
1JS15CS002
Enter the name and branch:
ADARSH
CSE
Enter the semester and phone number:
3
9753124680
Enter the USN:
1JS15CS003
Enter the name and branch:
AKSHAY
CSE
Enter the semester and phone number:
3
9078563412
SINGLY LINKED LIST IMPLEMENTATION
1.Create
2.Stack operation
3.Queue operation
4.Deletion from end
5.Display
6.Exit
Enter your choice:
2
Stack implementation
1.Push
2.Pop
3.Display
4.Go back to main menu
1
Enter the USN:
1JS15CS004
Enter the name and branch:
BHARGAV
CSE
Enter the semester and phone number:
3

Dept. of CS&E , JSSATEB Page 35


Data Structures Laboratory Manual

9631356789
Stack implementation
1.Push
2.Pop
3.Display
4.Go back to main menu
2
The deleted node is:
1JS15CS004 BHARGAV CSE 3 9631356789
Stack implementation
1.Push
2.Pop
3.Display
4.Go back to main menu
4
SINGLY LINKED LIST IMPLEMENTATION
1.Create
2.Stack operation
3.Queue operation
4.Deletion from end
5.Display
6.Exit
Enter your choice:
3
Queue implementation
1.Insert
2.Delete
3.Display
4.Go back to main menu
1
Enter the USN:
1JS15CS005
Enter the name and branch:
BHAIRAVI
ISE
Enter the semester and phone number:
3
9876543210
Queue implementation
1.Insert
2.Delete
3.Display
4.Go back to main menu
2
The deleted node is:
1JS15CS003 AKSHAY CSE 3 9078563412

Dept. of CS&E , JSSATEB Page 36


Data Structures Laboratory Manual

Queue implementation
1.Insert
2.Delete
3.Display
4.Go back to main menu
4
SINGLY LINKED LIST IMPLEMENTATION
1.Create
2.Stack operation
3.Queue operation
4.Deletion from end
5.Display
6.Exit
Enter your choice:
4
The deleted contents are:
1JS15CS005 BHAIRAVI ISE 3 9876543210
SINGLY LINKED LIST IMPLEMENTATION
1.Create
2.Stack operation
3.Queue operation
4.Deletion from end
5.Display
6.Exit
Enter your choice:
5
USN NAME BRANCH SEM PHNO
1JS15CS002 ADARSH CSE 3 9753124680
1JS15CS001 ABHI CSE 3 9876543210
Number of nodes:2
SINGLY LINKED LIST IMPLEMENTATION
1.Create
2.Stack operation
3.Queue operation
4.Deletion from end
5.Display
6.Exit
Enter your choice:
6

Dept. of CS&E , JSSATEB Page 37


Data Structures Laboratory Manual

LAB 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

ABOUT THE EXPERIMENT :

Doubly-linked list is a more sophisticated form of linked list data structure. Each node of the list
contain two references (or links) – one to the previous node and other to the next node. The
previous link of the first node and the next link of the last node points to NULL. In comparison
to singly-linked list, doubly-linked list requires handling of more pointers but less information is
required as one can use the previous links to observe the preceding element. It has a dynamic
size, which can be determined only at run time.

Basic operations of a Doubly -linked list are:

1. Insert – Inserts a new element at the end of the list.


2. Delete – Deletes any node from the list.
3. Find – Finds any node in the list.
4. Print – Prints the list.

ALGORITHM:

The node of a linked list is a structure with fields data (which stored the value of the node),
*previous (which is a pointer of type node that stores the address of the previous node) and *next
(which is a pointer of type node that stores the address of the next node).

Two nodes *start (which always points to the first node of the linked list) and *temp (which
is used to point to the last node of the linked list) are initialized. Initially temp = start, temp-
>prevoius = NULL and temp->next = NULL. Here, we take the first node as a dummy node. The
first node does not contain data, but it used because to avoid handling special cases in insert and
delete functions.

Functions –
1. Insert – This function takes the start node and data to be inserted as arguments. New node is
inserted at the end so, iterate through the list till we encounter the last node. Then,
allocate memory for the new node and put data in it. Lastly, store the address of the
previous node in the previous field of the new node and address in the next field of the
new node as NULL.

Dept. of CS&E , JSSATEB Page 38


Data Structures Laboratory Manual

2. Delete - This function takes the start node (as pointer) and data to be deleted as
arguments. Firstly, go to the node for which the node next to it has to be deleted,

If that node points to NULL (i.e. pointer->next=NULL) then the element to be


deleted is not present in the list.

Else, now pointer points to a node and the node next to it has to be removed, declare
a temporary node (temp) which points to the node which has to be removed. Store the address of
the node next to the temporary node in the next field of the node pointer (pointer->next =
temp->next) and also link the pointer and the node next to the node to be deleted
(temp->prev = pointer). Thus, by breaking the link we removed the node which is next
to the pointer (which is also temp). Because we deleted the node, we no longer require the
memory used for it, free() will de-allocate the memory.

3. Find - This function takes the start node (as pointer) and data value of the node (key) to
be found as arguments. First node is dummy node so, start with the second node. Iterate through
the entire linked list and search for the key. Until next field of the pointer is equal to NULL,
check if pointer->data = key. If it is then the key is found else, move to the next node and search
(pointer = pointer -> next). If key is not found return 0, else return 1.

4. Print - function takes the start node (as pointer) as an argument. If pointer = NULL, then
there is no element in the list. Else, print the data value of the node (pointer->data) and move to
the next node by recursively calling the print function with pointer->next sent as an argument.

PROGRAM CODE :

#include<stdio.h>
#include<conio.h>
#include<process.h>
typedef struct node
{
char ssn[10],name[20],dept[10],desig[10],phno[10];
int sal;
struct node *back;
struct node*forw;
}NODE;
NODE *start=NULL;
void create();
void display();
int count_nodes();
void insert_front();
void del_front();
void insert_end();

Dept. of CS&E , JSSATEB Page 39


Data Structures Laboratory Manual

void del_end();
void main_menu();
void input_deque();
void output_deque();

void main()
{
clrscr();
main_menu();
}
void main_menu()
{
int ch;
while(1)
{
printf("\n DOUBLY LINKED LIST IMPLEMENTATION\n");
printf("\n 1. CREATE LIST\n");
printf("\n 2. INPUT RESTRICTED DEQUE\n");
printf("\n 3. OUTPUT RESTRICTED DEQUE\n");
printf("\n 4. DISPLAY\n");
printf("\n 5.EXIT\n");
printf("\n ENTER YOUR CHOICE\n");
scanf("%d",&ch);
switch(ch)
{
case 1: create();
break;
case 2: input_deque();
break;
case 3: output_deque();
break;
case 4: display();
break;
case 5: exit(0);
default: printf("\n INVALID CHOICE\n");
}
}
}
void create()
{
int i,n;
NODE*newnode,*curptr=NULL;
printf("\n enter the number of nodes\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{

Dept. of CS&E , JSSATEB Page 40


Data Structures Laboratory Manual

newnode=(NODE*)malloc(sizeof(NODE));
printf("\nenter the ssn\n");
scanf("%s",newnode->ssn);
printf("\n enter name department and designation\n");
scanf("%s%s%s",newnode->name,newnode->dept,newnode->desig);
printf("\n enter salary\n");
scanf("%d",&newnode->sal);
printf("\n enter phone number\n");
scanf("%s",newnode->phno);
if(start==NULL)
{
newnode->forw=NULL;
newnode->back=NULL;
start=newnode;
}
else
{
curptr=start;
while(curptr->forw!=NULL)
curptr->forw=curptr;
newnode->back=curptr;
newnode->forw=NULL;
curptr->forw=newnode;
}
}
}
void display()
{
NODE* curptr=NULL;
if(start==NULL)
printf("\n LIST EMPTY\n");
else
{
curptr=start;
printf("\n The contents are\n");
printf("\n SSN\tNAME\tDEPT\tDESIG\tSALARY\tPHONE\n");
while(curptr!=NULL)
{
printf("\n %s\t%s\t%s\t%s\t%d\t%s\n",curptr->ssn,curptr->name,curptr->dept,curptr-
>desig,curptr->sal,curptr->phno);
curptr=curptr->forw;
}
printf("\n TOTAL NUMBER OF NODES IS %d",count_nodes());
}
}
int count_nodes()

Dept. of CS&E , JSSATEB Page 41


Data Structures Laboratory Manual

{
NODE *curptr=NULL;
int ctr=0;
if(start==NULL)
return 0;
else
{
curptr=start;
while(curptr!=NULL)
{
ctr++;
curptr=curptr->forw;
}
}
return ctr;
}
void input_deque()
{
int ch;
while(1)
{
printf("\n INPUT RESTRICTED DEQUE\n");
printf("\n 1. insert from rear\n");
printf("\n 2. delete from rear\n");
printf("\n 3. delete from front\n");
printf("\n 4. display\n");
printf("\n 5. exit from deque\n");
printf("\n enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert_end();
break;
case 2: del_end();
break;
case 3: del_front();
break;
case 4: display();
break;
case 5: main_menu();
break;
default: printf("\n wrong choice\n");
}
}
}
void insert_end()

Dept. of CS&E , JSSATEB Page 42


Data Structures Laboratory Manual

{
NODE*newnode,*curptr=NULL;
newnode=(NODE*)malloc(sizeof(NODE));
printf("\nenter the ssn\n");
scanf("%s",newnode->ssn);
printf("\n enter name department and designation\n");
scanf("%s%s%s",newnode->name,newnode->dept,newnode->desig);
printf("\n enter salary\n");
scanf("%d",&newnode->sal);
printf("\n enter phone number\n");
scanf("%s",newnode->phno);
if(start==NULL)
{
newnode->forw=NULL;
newnode->back=NULL;
start=newnode;
}
else
{
curptr=start;
while(curptr->forw!=NULL)
curptr=curptr->forw;
newnode->back=curptr;
newnode->forw=NULL;
curptr->forw=newnode;
}

}
void del_end()
{
NODE *curptr=NULL;
if(start==NULL)
printf("\n LIST EMPTY\n");
else if(start->forw==NULL)
{
curptr=start;
printf("\n last node\n");
start=NULL;
free(curptr);
}
else
{
curptr=start;
while(curptr->forw!=NULL)
curptr=curptr->forw;
curptr->back->forw=NULL;

Dept. of CS&E , JSSATEB Page 43


Data Structures Laboratory Manual

free(curptr);
}
}
void del_front()
{
NODE *curptr=NULL;
if(start==NULL)
printf("\n LIST EMPTY\n");
else
{
curptr=start;
start=start->forw;
start->back=NULL;
free(curptr);
}
}
void output_deque()
{
int ch;
while(1)
{
printf("\n OUTPUT RESTRICTED DEQUE\n");
printf("\n 1. insert from rear\n");
printf("\n 2. insert from front\n");
printf("\n 3. delete from front\n");
printf("\n 4. display\n");
printf("\n 5. exit from deque\n");
printf("\n enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert_end();
break;
case 2: insert_front();
break;
case 3: del_front();
break;
case 4: display();
break;
case 5: main_menu();
break;
default: printf("\n wrong choice\n");
}
}
}
void insert_front()

Dept. of CS&E , JSSATEB Page 44


Data Structures Laboratory Manual

{
NODE*newnode=NULL;
newnode=(NODE*)malloc(sizeof(NODE));
printf("\nenter the ssn\n");
scanf("%s",newnode->ssn);
printf("\n enter name department and designation\n");
scanf("%s%s%s",newnode->name,newnode->dept,newnode->desig);
printf("\n enter salary\n");
scanf("%d",&newnode->sal);
printf("\n enter phone number\n");
scanf("%s",newnode->phno);
newnode->forw=start;
newnode->back=NULL;
start->back=newnode;
start=newnode;
}

OUTPUT:

Double ended
1.create
2.I/P restricted
3.O/P restricted
4.displa
Enter the value of n
2
Enter SSN
IR001
Enter name,dept
KUMAR
CSE
enter the salary and ph no
5000
9876543210
Enter SSN
IR002
Enter name,dept
RAJU
ISE
enter the salary and ph no
6000
9786543210
Double ended
1.create
2.I/P restricted

Dept. of CS&E , JSSATEB Page 45


Data Structures Laboratory Manual

3.O/P restricted
4.display
5.Exit
Enter your choice
2
I/P restricted Queue
1.insert_end
2.del_front
3.del_rear
4.output
5.main_menu
Enter your choice
1
Enter SSN
IR003
Enter name,dept
HARISH
MECH
enter the salary and ph no
8000
9078563412
I/P restricted Queue
1.insert_end
2.del_front
3.del_rear
4.output
5.main_menu
Enter your choice
2
the content deleted is IR001 KUMAR CSE 5000 9876543210
I/P restricted Queue
1.insert_end
2.del_front
3.del_rear
4.output
5.main_menu
Enter your choice
5
Double ended
1.create
2.I/P restricted
3.O/P restricted
4.display
5.Exit
Dept. of CS&E , JSSATEB Page 46
Data Structures Laboratory Manual

Enter your choice


3
O/P RESTRICTED
1.Insert from front
2.Insert from end
3.Delete from front
4.Display
5.Go back to main menu
Enter your choice:
1
Enter the SSN
IR004
Enter name ,dept
MANISH
IEE
Enter salary and phno
7000
9078563412
O/P RESTRICTED
1.Insert from front
2.Insert from end
3.Delete from front
4.Display
5.Go back to main menu
Enter your choice:
3
the content deleted is IR004 MANISH IEE 9078563412
O/P RESTRICTED
1.Insert from front
2.Insert from end
3.Delete from front
4.Display
5.Go back to main menu
Enter your choice:
5
Double ended
1.create
2.I/P restricted
3.O/P restricted
4.display
5.Exit
Enter your choice
4
SSN Name dept sal phno
Elements are IR002 RAJU ISE 6000 9786543210

Dept. of CS&E , JSSATEB Page 47


Data Structures Laboratory Manual

Elements are IR003 HARISH MECH 8000 9078563412


No of nodes is 2
Double ended
1.create
2.I/P restricted
3.O/P restricted
4.display
5.Exit
Enter your choice
5

Dept. of CS&E , JSSATEB Page 48


Data Structures Laboratory Manual

LAB PROGRAM 9

9(a) 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) Support the program with appropriate functions for each of the above
operations

ABOUT THE EXPERIMENT :

Circular linked list is a more complicated linked data structure. In this the elements can be placed
anywhere in the heap memory unlike array which uses contiguous locations. Nodes in a linked
list are linked together using a next field, which stores the address of the next node in the next
field of the previous node i.e. each node of the list refers to its successor and the last node points
back to the first node unlike singly linked list. It has a dynamic size, which can be determined
only at run time.

Basic operations of a singly-linked list are:


1. Insert – Inserts a new element at the end of the list.
2. Delete – Deletes any node from the list.
3. Find – Finds any node in the list.
4. Print – Prints the list.

ALGORITHM:

The node of a linked list is a structure with fields data (which stored the value of the node) and
*next (which is a pointer of type node that stores the address of the next node).

Two nodes *start (which always points to the first node of the linked list) and *temp (which is
used to point to the last node of the linked list) are initialized. Initially temp = start and temp-
>next = start. Here, we take the first node as a dummy node. The first node does not contain data,
but it used because to avoid handling special cases in insert and delete functions.

Functions:
1.Insert – This function takes the start node and data to be inserted as arguments. New node is
inserted at the end so, iterate through the list till we encounter the last node. Then,
allocate memory for the new node and put data in it. Lastly, store the address of the first
node (start) in the next field of the new node.

2. Delete - This function takes the start node (as pointer) and data to be deleted as arguments.
Firstly, go to the node for which the node next to it has to be deleted,

If that node points to NULL (i.e. pointer->next=NULL) then the element to be deleted
is not present in the list.

Dept. of CS&E , JSSATEB Page 49


Data Structures Laboratory Manual

Else, now pointer points to a node and the node next to it has to be removed, declare
a temporary node (temp) which points to the node which has to be removed. Store the address of
the node next to the temporary node in the next field of the node pointer (pointer->next =
temp->next). Thus, by breaking the link we removed the node which is next to the pointer
(which is also temp). Because we deleted the node, we no longer require the memory used
for it, free() will deallocate the memory.

3. Find - This function takes the start node (as pointer) and data value of the node (key)
to be found as arguments. A pointer start of type node is declared, which points to the
head node of the list (node *start = pointer). First node is dummy node so, start with the
second node. Iterate through the entire linked list and search for the key.
Until next field of the pointer is equal to start, check if pointer->data = key. If it is
then the key is found else, move to the next node and search
(pointer = pointer -> next). If key is not found return 0, else return 1.

4. Print - function takes the start node (as start) and the next node (as pointer) as arguments. If
pointer = start, then there is no element in the list. Else, print the data value of the node (pointer-
>data) and move to the next node by recursively calling the print function with pointer->next
sent as an argument.

PROGRAM CODE :

#include<stdio.h>
#include<alloc.h>
#include<math.h>
struct node
{
int cf, px, py, pz;
int flag;
struct node *link;
};
typedef struct node NODE;
NODE* getnode()
{
NODE *x;
x=(NODE*)malloc(sizeof(NODE));
if(x==NULL)
{
printf("Insufficient memory\n");
exit(0);
}
return x;
}
void display(NODE *head)
{
NODE *temp;

Dept. of CS&E , JSSATEB Page 50


Data Structures Laboratory Manual

if(head->link==head)
{
printf("Polynomial does not exist\n");
return;
}
temp=head->link;
printf("\n");
while(temp!=head)
{
printf("%d x^%d y^%d z^%d",temp->cf,temp->px,temp->py,temp->pz);
if(temp->link != head)
printf(" + ");
temp=temp->link;
}
printf("\n");
}
NODE* insert_rear(int cf,int x,int y,int z,NODE *head)
{
NODE *temp,*cur;
temp=getnode();
temp->cf=cf;
temp->px=x;
temp->py=y;
temp->pz=z;
cur=head->link;
while(cur->link!=head)
{
cur=cur->link;
}
cur->link=temp;
temp->link=head;
return head;
}
NODE* read_poly(NODE *head)
{
int px, py, pz, cf, ch;
printf("\nEnter coeff: ");
scanf("%d",&cf);
printf("\nEnter x, y, z powers(0-indiacate NO term): ");
scanf("%d%d%d", &px, &py, &pz);
head=insert_rear(cf,px,py,pz,head);
printf("\nIf you wish to continue press 1 otherwise 0: ");
scanf("%d", &ch);
while(ch != 0)
{
printf("\nEnter coeff: ");

Dept. of CS&E , JSSATEB Page 51


Data Structures Laboratory Manual

scanf("%d",&cf);
printf("\nEnter x, y, z powers(0-indiacate NO term): ");
scanf("%d%d%d", &px, &py, &pz);
head=insert_rear(cf,px,py,pz,head);
printf("\nIf you wish to continue press 1 otherwise 0: ");
scanf("%d", &ch);
}
return head;
}
NODE* add_poly(NODE *h1,NODE *h2,NODE *h3)
{
NODE *p1,*p2;
int x1,x2,y1,y2,z1,z2,cf1,cf2,cf;
p1=h1->link;
while(p1!=h1)
{
x1=p1->px;
y1=p1->py;
z1=p1->pz;
cf1=p1->cf;
p2=h2->link;
while(p2!=h2)
{
x2=p2->px;
y2=p2->py;
z2=p2->pz;
cf2=p2->cf;
if(x1==x2 && y1==y2 && z1==z2)
break;
p2=p2->link;
}
if(p2!=h2)
{
cf=cf1+cf2;
p2->flag=1;
if(cf!=0)
h3=insert_rear(cf,x1,y1,z1,h3);
}
else
h3=insert_rear(cf1,x1,y1,z1,h3);
p1=p1->link;
}
p2=h2->link;
while(p2!=h2)
{
if(p2->flag==0)

Dept. of CS&E , JSSATEB Page 52


Data Structures Laboratory Manual

h3=insert_rear(p2->cf,p2->px,p2->py,p2->pz,h3);
p2=p2->link;
}
return h3;
}
void evaluate(NODE *h1)
{
NODE *head;
int x, y, z;
float result=0.0;
head=h1;
printf("\nEnter x, y, z, terms to evaluate:\n");
scanf("%d%d%d", &x, &y, &z);
while(h1->link != head)
{
result = result + (h1->cf * pow(x,h1->px) * pow(y,h1->py) * pow(z,h1->pz));
h1=h1->link;
}
result = result + (h1->cf * pow(x,h1->px) * pow(y,h1->py) * pow(z,h1->pz));
printf("\nPolynomial result is: %f", result);
}
void main()
{
NODE *h1,*h2,*h3;
int ch;
h1=getnode();
h2=getnode();
h3=getnode();
h1->link=h1;
h2->link=h2;
h3->link=h3;
while(1)
{
printf("\n\n1.Evaluate polynomial\n2.Add two polynomials\n3.Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: printf("\nEnter polynomial to evaluate:\n");
h1=read_poly(h1);
display(h1);
evaluate(h1);
break;
case 2: printf("\nEnter the first polynomial:");
h1=read_poly(h1);
printf("\nEnter the second polynomial:");

Dept. of CS&E , JSSATEB Page 53


Data Structures Laboratory Manual

h2=read_poly(h2);
h3=add_poly(h1,h2,h3);
printf("\nFirst polynomial is: ");
display(h1);
printf("\nSecond polynomial is: ");
display(h2);
printf("\nThe sum of 2 polynomials is: ");
display(h3);
break;
case 3: exit(0);
break;
default: printf("\nInvalid entry");
break;
}
}
}

OUTPUT :
1. Evaluate polynomial
P(x,y,z) = 6x2y2z4yz5+3x3yz+2xy5z-2xyz3
2. Add two polynomials
3. Exit
Enter your choice: 1
Enter polynomial to evaluate:
Enter coeff: 6
Enter x, y, z powers (0-indiacate NO term:
221
If you wish to continue press 1 otherwise 0:
1 Enter coeff: -4
Enter x, y, z powers (0-indiacate NO term: 0
15
If you wish to continue press 1 otherwise 0:
1
Enter coeff: 3
Enter x, y, z powers (0-indiacate NO term: 3 1 1

If you wish to continue press 1


otherwise 0: 1
Enter coeff: 2
Enter x, y, z powers (0-indiacate NO term: 1 5 1
If you wish to continue press 1
otherwise 0:
Enter coeff: -2
Enter x, y, z powers (0-indiacate NO term: 1 1 3
If you wish to continue press 1 otherwise 0: 0
Polynomial is:

Dept. of CS&E , JSSATEB Page 54


Data Structures Laboratory Manual

6 x^2 y^2 z^1 + -4 x^0 y^1 z^5 + 3 x^3 y^1 z^1 + 2 x^1 y^5 z^1 + -2 x^1 y^1 z^3
Enter x, y, z, terms to
evaluate: 1 1 1
Polynomial result is: 5.000000

1. Evaluate polynomial P(x,y,z) = 6x2y2z4yz5+3x3yz+2xy5z-2xyz3


2. Add two polynomials
3. Exit
Enter your choice: 2

Enter 1st polynomial:


Enter coeff: 4
Enter x, y, z powers (0-indiacate NO term: 2 2 2
If you wish to continue press 1 otherwise 0: 1
Enter coeff: 3
Enter x, y, z powers (0-indiacate NO term: 1 1 2
If you wish to continue press 1 otherwise 0: 0
Enter 2nd polynomial:
Enter coeff: 6
Enter x, y, z powers (0-indiacate NO term:
222
If you wish to continue press 1 otherwise 0:
0
Polynomial is:
1st Polynomial is:
4 x^2 y^2 z^2 + 3 x^1 y^1 z^2
2nd Polynomial is:
6 x^2 y^2 z^2
Added polynomial: 10 x^2 y^2 z^2 + 3 x^1 y^1 z^2

1. Evaluate polynomial P(x,y,z) = 6x2y2z4yz5+3x3yz+2xy5z-2xyz3


2. Add two polynomials
3. Exit
Enter your choice:
3

Dept. of CS&E , JSSATEB Page 55


Data Structures Laboratory Manual

LAB 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 Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Delete an element (ELEM) from BST
e. Exit

ABOUT THE EXPERIMENT :

A tree is a connected, acyclic, unidirectional graph. It emulates a tree structure with a set of
linked nodes. The topmost node in a tree is called the root node, node of a tree that has child
nodes is called an internal node or inner node and the bottom most nodes are called a leaf node.
The root is a node that has no parent; it can have only child nodes. Leaves, on the other hand,
have no children. The simplest form of a tree is a Binary Tree which has a root node and two
subtrees (which is a portion of a tree data structure that can be viewed as a complete tree in
itself) - left and right.

A Binary Search Tree is a binary tree in which if a node has value N, all values in its left sub-tree
are less than N, and all values in its right sub-tree are greater than N. This property called binary
search tree property holds for each and every node in the tree.

Basic operations of Binary Search tree are:

1. Finding a node with a specific data value.


2. Finding a node with minimum or maximum data value.
3. Insertion and deletion of a node.
4. Three (preorder, postorder and inorder) operations for depth-first traversal of a tree
a. Preorder: Visit a node before traversing it’s subtrees
b. Inorder: Visit a node after traversing it’s left subtree but before traversing it’s
right subtree
c. Postorder: Visit a node after traversing all of it’s subtrees

Binary search tree has three properties: data stands for the value of the node, *left is the left
subtree of a node and *right (a pointer of type struct treeNode) is the right subtree of a node.

ALGORITHM:

Tree’s node (treeNode) structure is defined with fields data, *left (pointer to the structure
treeNode basically denotes the left subtree of a node) and *right (pointer to the structure
treeNode basically denotes the right subtree of a node).

Dept. of CS&E , JSSATEB Page 56


Data Structures Laboratory Manual

First initialize the value of the root (pointer to the structure treeNode) with NULL.

TreeNode *root = NULL


Functions:

1.Insert function - This function takes the root node of the tree and the value (data) of the
node to be inserted as arguments, and returns the pointer to the root node after the new
node has been inserted.
If the node is equal to NULL (i.e. it is an empty tree)
o Initialize a temp (pointer to the structure treeNode)node and store the data in temp -> data.
o Initialize temp -> left & temp -> right with NULL (empty left and right subtree).
o Return temp.
Otherwise, if data > data value of the node (node->data), then insert the new node at the
right subtree.
node->right = Insert(node->right , data)

Else, if data < data value of the node (node->data), then insert the new node at the
left subtree.

node->left = Insert(node->left , data)

Else there is nothing to do as the data is already in the tree.

Return the root node.


2.Delete function - This function takes the root node of the tree and the value (data) of the node
to be deleted as arguments, and returns the pointer to the root node after replacing the deleted
node.
If the node is equal to NULL (i.e. it is an empty tree). So, return the same node
without deletion.

Else, if data > data value of the node (node->data), then move to the right subtree.
node->right = Delete(node->right , data)

Else, if data < data value of the node (node->data), then move to the left subtree.
node->left = Delete(node->left , data)

Else, now We can delete this node and replace with either minimum element in
the right sub tree or maximum element in the left subtree
o If the node to be deleted has both left and right subtree replace it with the
minimum element in the right sub tree, with the help of a temporary node.
Find the minimum element in the right subtree using FindMin function
and store it in a temporary node. Now, replace the value of the node to be
deleted by the value of the temporary node. After replacing, we have to
delete the node that replaces the deleted node.
o Else, if there is only one or zero children then we can connect its parent
to its child or directly remove it from the tree. After all this free the

Dept. of CS&E , JSSATEB Page 57


Data Structures Laboratory Manual

temporary node used.

Return the root node.


3. FindMin function - This function takes the root node of the tree as an argument, and
returns the minimum node of the tree.
If node is equal to NULL, then there is no element in the tree. So, return NULL
(Minimum not found).

Else, if there is a left subtree of the node, go to the left sub tree to find the
minimum element. FindMin(node->left).

Else, return the same node as it will be the minimum node if it doesn’t have a left
subtree.

4. FindMax function - This function takes the root node of the tree as an argument, and
returns the maximum node of the tree.

If node is equal to NULL, then there is no element in the tree. So, return NULL
(Maximum not found).

Else, if there is a right subtree of the node, go to the right sub tree to find the
maximum element. FindMax(node->right).

Else, return the same node as it will be the maximum node if it doesn’t have a
right subtree.

5. Find function - This function takes the root node of the tree and the value (data) of the
node to be deleted as arguments, and returns the found node of the tree.
If node is equal to NULL, then there is no element in the tree. So, return NULL
(Element not found).

If there is a right subtree of the node, go to the right sub tree to find the required
element. Find(node->right, data).

Else, if there is a left subtree of the node, go to the left sub tree to find the
minimum element. Find(node->left).

Else, the node is found in either the left or right subtree. Return the node.
The returned node is stored in a temporary node. If that temporary node = NULL,
then the node is not found else it is found.
6. Print Inorder function – This function takes the root node of the tree as an argument and
visits all the nodes in the tree in in-order and prints the value of the nodes as they are
visited.
If node is equal to NULL, then there is no element in the tree. Return to the main
function.

Dept. of CS&E , JSSATEB Page 58


Data Structures Laboratory Manual

Visit the left subtree of the node first, then print the value of that node and lastly
visit the right subtree of that node.
o PrintInorder(node->left)
o Print node->data
o PrintInorder(node->right)
7. Print Preorder function – This function takes the root node of the tree as an argument and
visits all the nodes in the tree in pre-order and prints the value of the nodes as they are visited.
If node is equal to NULL, then there is no element in the tree. Return to the main
function.

Print the value of the node first, then visit the left subtree of that node and lastly
visit the right subtree of that node.
o Print node->data
oPrintPreorder(node->left)
o PrintPreorder(node->right)

8. PrintPostorder function – This function takes the root node of the tree as an argument and
visits all the nodes in the tree in post-order and prints the value of the nodes as they are visited.
If node is equal to NULL, then there is no element in the tree. Return to the main
function.

Visit the left subtree of the node first, then visit the right subtree of that node and
lastly print the value of that node.
o PrintPostorder(node->left)
o PrintPostorder(node->right)
o Print node->data

PROGRAM CODE :

#include <stdio.h>
#include <stdlib.h>
struct BST
{
int data;
struct BST *left;
struct BST *right;
};
typedef struct BST NODE;

NODE *node;

NODE* createtree(NODE *node, int data)


{
if (node == NULL)
{

Dept. of CS&E , JSSATEB Page 59


Data Structures Laboratory Manual

NODE *temp;
temp= (NODE*)malloc(sizeof(NODE));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
if (data < (node->data))
{
node->left = createtree(node->left, data);
}
else
if (data > node->data)
{
node -> right = createtree(node->right, data);
}
return node;
}
NODE* search(NODE *node, int data)
{
if(node == NULL)
printf("\nElement not found");
else
if(data < node->data)
{
node->left=search(node->left, data);
}
else
if(data > node->data)
{
node->right=search(node->right, data);
}
else
printf("\nElement found is: %d", node->data);
return node;
}
void inorder(NODE *node)
{
if(node != NULL)
{
inorder(node->left);
printf("%d\t", node->data);
inorder(node->right);
}
}
void preorder(NODE *node)
{

Dept. of CS&E , JSSATEB Page 60


Data Structures Laboratory Manual

if(node != NULL)
{
printf("%d\t", node->data);
preorder(node->left);
preorder(node->right);
}
}
void postorder(NODE *node)
{
if(node != NULL)
{
postorder(node->left);
postorder(node->right);
printf("%d\t", node->data);
}
}
NODE* findMin(NODE *node)
{
if(node==NULL)
{
return NULL;
}
if(node->left)
return findMin(node->left);
else
return node;
}
NODE* del(NODE *node, int data)
{
NODE *temp;
if(node == NULL)
{
printf("\nElement not found");
}
else
if(data < node->data)
{
node->left = del(node->left, data);
}
else
if(data > node->data)
{
node->right = del(node->right, data);
}
else
{

Dept. of CS&E , JSSATEB Page 61


Data Structures Laboratory Manual

/* Now We can delete this node and replace with either minimum element in the right sub tree or
maximum element in the left subtree */
if(node->right && node->left)
{
/* Here we will replace with minimum element in the right sub tree */
temp = findMin(node->right);
node -> data = temp->data;
/* As we replaced it with some other node, we have to delete that node */
node -> right = del(node->right,temp->data);
}
else
{
/* If there is only one or zero children then we can directly remove it from the tree and connect
its parent to its child */
temp = node;
if(node->left == NULL)
node = node->right;
else
if(node->right == NULL)
node = node->left;
free(temp);
/* temp is longer required */
}
}
return node;
}
void main()
{
int data, ch, i, n;
NODE *root=NULL;
while (1)
{
printf("\n1.Insertion in Binary Search Tree");
printf("\n2.Search Element in Binary Search Tree");
printf("\n3.Delete Element in Binary Search Tree");
printf("\n4.Inorder\n5.Preorder\n6.Postorder\n7.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1: printf("\nEnter N value: " );
scanf("%d", &n);
printf("\nEnter the values to create BST like(6,9,5,2,8,15,24,14,7,8,5,2)\n");
for(i=0; i<n; i++)
{
scanf("%d", &data);

Dept. of CS&E , JSSATEB Page 62


Data Structures Laboratory Manual

root=createtree(root, data); }
break;
case 2: printf("\nEnter the element to search: ");
scanf("%d", &data);
root=search(root, data);
break;
case 3:printf("\nEnter the element to delete: ");
scanf("%d", &data);
root=del(root, data);
break;
case 4: printf("\nInorder Traversal: \n");
inorder(root);
break;
case 5: printf("\nPreorder Traversal: \n");
preorder(root);
break;
case 6:
printf("\nPostorder Traversal: \n");
postorder(root);
break;
case 7: exit(0);
default:printf("\nWrong option");
break;
}
}
}

OUTPUT:
1. Insertion in Binary Search Tree
2. Search Element in Binary Search Tree
3. Delete Element in Binary Search Tree
4. Inorder
5. Preorder
6. Postorder
7. Exit
Enter your choice: 1
Enter N value: 12
Enter the values to create BST like(6,9,5,2,8,15,24,14,7,8,5,2)
6 9 5 2 8 15 24 14 7 8 5 2
1. Insertion in Binary Search Tree
2. Search Element in Binary Search Tree
3. Delete Element in Binary Search Tree
4. Inorder
5. Preorder
6. Postorder
7. Exit

Dept. of CS&E , JSSATEB Page 63


Data Structures Laboratory Manual

Enter your choice: 4

Inorder Traversal: 2 5 6 7 8 9 14 15 24

1. Insertion in Binary Search Tree


2. Search Element in Binary Search Tree
3. Delete Element in Binary Search Tree
4. Inorder
5. Preorder
6. Postorder
7. Exit
Enter your choice: 5
Preorder Traversal: 6 5 2 9 8 7 15 14 24

1. Insertion in Binary Search Tree


2. Search Element in Binary Search Tree
3. Delete Element in Binary Search Tree
4. Inorder
5. Preorder
6. Postorder
7. Exit
Enter your choice: 6
Postorder Traversal: 2 5 7 8 14 24 15 9 6

1. Insertion in Binary Search Tree


2. Search Element in Binary Search Tree
3. Delete Element in Binary Search Tree
4. Inorder
5. Preorder
6. Postorder
7. Exit
Enter your choice: 2
Enter the element to search: 24
Element found is: 24

1. Insertion in Binary Search Tree


2. Search Element in Binary Search Tree
3. Delete Element in Binary Search Tree
4. Inorder
5. Preorder
6. Postorder
7. Exit
Enter your choice: 2
Enter the element to search: 50
Element not found

Dept. of CS&E , JSSATEB Page 64


Data Structures Laboratory Manual

LAB 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 in a digraph using BFS method
c. Check whether a given graph is connected or not using DFS method.

ABOUT THE EXPERIMENT:

Breadth-First Search
Breadth-first search is one of the simplest algorithms for searching a graph. Given a graph and a
distinguished source vertex, breadth-first search explores the edges of the graph to find every
vertex reachable from source. It computes the distance (fewest number of edges) from source to
all reachable vertices and produces a “breadth-first tree” with source vertex as root, which
contains all such reachable vertices. It works on both directed and undirected graphs. This
algorithm uses a first-in, first-out Queue Q to manage the vertices.

ALGORITHM:

Input Format: Graph is directed and unweighted. First two integers must be number of vertices
and edges which must be followed by pairs of vertices which has an edge between them.

maxVertices represents maximum number of vertices that can be present in the graph.
vertices represent number of vertices and edges represent number of edges in the graph.
graph[i][j] represent the weight of edge joining i and j.
size[maxVertices] is initialed to{0}, represents the size of every vertex i.e. the
number of edges corresponding to the vertex.
visited[maxVertices]={0} represents the vertex that have been visited.

Initialize the graph.

For presentVertex = 0 to vertices if visited[presentVertex] is 0, i.e. if the vertex has


not been visited then call Bfs function. presentVertex represents the vertex that is being
tackled.

Bfs function is called to get the shortest path.

Bfs function: This function takes the graph obtained (graph[ ][ maxVertices]), pointer to the
array size and visited, and the presentValue as arguments.

visited[presentVertex] = 1 as the vertex has now been visited. Iterate through all the
vertices connected to the presentVertex and perform bfs on those vertices if they are not
visited before.
Create a queue Q using createQueue function and enqueue the presentVertex using

Dept. of CS&E , JSSATEB Page 65


Data Structures Laboratory Manual

Enqueue function.
Until the Q is not empty i.e. Q->size ≠ 0
• Store the front element of Q using Front function in presentVertex
• Print the vertex that is being visited now, which is presentVertex
• Remove the element from the front of Q using Dequeue function
• For iter=0 to size[presentVertex] – 1

If (!visited[graph[presentVertex][iter]])
visited[graph[presentVertex][iter]] = 1
Enqueue(Q,graph[presentVertex][iter])
Iter + 1
This for loop visits every vertex that is adjacent to the presentVertex and has not
been visited yet. These vertices are then inserted in the Q using Enqueue function
and their visited status is updated to 1.
Queue has five properties - capacity stands for the maximum number of elements Queue can
hold, Size stands for the current size of the Queue, elements is the array of elements, front is the
index of first element (the index at which we remove the element) and rear is the index of last
element (the index at which we insert the element). Functions on Queue

1. createQueue function takes argument the maximum number of elements the Queue can hold,
creates a Queue according to it and returns a pointer to the Queue. It initializes Q->size to 0, Q-
>capacity to maxElements, Q->front to 0 and Q->rear to -1.

2. enqueue function - This function takes the pointer to the top of the queue Q and the item
(element) to be inserted as arguments. Check for the emptiness of queue
a. If Q->size is equal to Q->capacity, we cannot push an element into Q as there is
no space for it.
b. Else, enqueue an element at the end of Q, increase its size by one. Increase the
value of Q->rear to Q->rear + 1. As we fill the queue in circular fashion, if
Q->rear is equal to Q->capacity make Q->rear = 0. Now, Insert the element in its
rear side
Q->elements[Q->rear] = element
3. dequeue function - This function takes the pointer to the top of the stack S as an
argument.
a. If Q->size is equal to zero, then it is empty. So, we cannot dequeue.
b. Else, remove an element which is equivalent to incrementing index of front by
one. Decrease the size by 1. As we fill elements in circular fashion,
if Q->frontequal to Q->capacity make Q->front=0.
4. front function – This function takes the pointer to the top of the queue Q as an argument and
returns the front element of the queue Q. It first checks if the queue is empty
(Q->size is equal to zero). If it’s not it returns the element which is at the front of the queue.

Depth-First Search

Depth-first search algorithm searches deeper in graph whenever possible. In this, edges are
explored out of the most recently visited vertex that still has unexplored edges leaving it. When

Dept. of CS&E , JSSATEB Page 66


Data Structures Laboratory Manual

all the vertices of that vertex’s edges have been explored, the search goes backtracks to explore
edges leaving the vertex from which a vertex was recently discovered. This process continues
until we have discovered all the vertices that are reachable from the original source vertex. It
works on both directed and undirected graphs.

ALGORITHM:

Input Format: Graph is directed and unweighted. First two integers must be number of vertices
and edges which must be followed by pairs of vertices which has an edge between them.

maxVertices represents maximum number of vertices that can be present in the graph.
vertices represent number of vertices and edges represent number of edges in the graph.

graph[i][j] represent the weight of edge joining i and j.


size[maxVertices] is initialed to{0}, represents the size of every vertex i.e. the number of
edges corresponding to the vertex.

visited[maxVertices]={0} represents the vertex that have been visited.

Initialize the graph.

For presentVertex = 0 to vertices if visited[presentVertex] is 0, i.e. if the vertex has not


been visited then call Dfs function. presentVertex represents the vertex that is being
tackled.

Dfs function is called to get the shortest path.

Dfs function: This function takes the graph obtained (graph[ ][ maxVertices]), pointer to the
array size and visited, and the presentValue as arguments.
Print the vertex that is being visited now, which is presentVertex visited[presentVertex]
= 1 as the vertex has now been visited.

Iterate through all the vertices connected to the presentVertex and perform Dfs on
those vertices that are not visited before

For iter=0 to size[presentVertex]-1


if (!visited[graph[presentVertex][iter]])
Dfs(graph,size,graph[presentVertex][iter],visited)
iter + 1

PROGRAM CODE:

#include<stdio.h>
#include<conio.h>
int a[10][10], n, m, i, j, source, s[10], b[10];
int visited[10];

Dept. of CS&E , JSSATEB Page 67


Data Structures Laboratory Manual

void create()
{
printf("\nEnter the number of vertices of the digraph: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix of the graph:\n");
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
scanf("%d", &a[i][j]);
}
void bfs()
{
int q[10], u, front=0, rear=-1;
printf("\nEnter the source vertex to find other nodes reachable or not: ");
scanf("%d", &source);
q[++rear] = source;
visited[source] = 1;
printf("\nThe reachable vertices are: ");
while(front<=rear)
{
u = q[front++];
for(i=1; i<=n; i++)
{
if(a[u][i] == 1 && visited[i] == 0)
{
q[++rear] = i;
visited[i] = 1;
printf("\n%d", i);
}
}
}
}
void dfs(int source)
{
int v, top = -1;
s[++top] = 1;
b[source] = 1;
for(v=1; v<=n; v++)
{
if(a[source][v] == 1 && b[v] == 0)
{
printf("\n%d -> %d", source, v);
dfs(v);
}
}
}
void main()

Dept. of CS&E , JSSATEB Page 68


Data Structures Laboratory Manual

{
int ch;
while(1)
{
printf("\n1.Create Graph\n2.BFS\n3.Check graph connected or not(DFS)\n4.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: create();
break;
case 2:
bfs();
for(i=1;i<=n;i++)
if(visited[i]==0)
printf("\nThe vertex that is not rechable %d" ,i);
break;
case 3: printf("\nEnter the source vertex to find the connectivity: ");
scanf("%d",&source);
m=1;
dfs(source);
for(i=1;i<=n;i++)
{
if(b[i]==0) m=0;
}
if(m==1)
printf("\nGraph is Connected");
else
printf("\nGraph is not Connected");
break;
default: exit(0);
}
}
}

OUTPUT :
1. Create Graph 2.BFS 3.Check graph connected or not (DFS) 4.Exit
Enter your choice: 1
Enter the number of vertices of the digraph: 4
Enter the adjacency matrix of the graph:
0011
0000
0100
0100

1. Create Graph 2.BFS 3.Check graph connected or not (DFS) 4.Exit

Dept. of CS&E , JSSATEB Page 69


Data Structures Laboratory Manual

Enter your choice: 2


Enter the source vertex to find other nodes reachable or not: 1
3
4
2

1. Create Graph 2.BFS 3.Check graph connected or not (DFS) 4.Exit


Enter your choice: 3
Enter the source vertex to find the connectivity: 1
1 -> 3
3 -> 2
1 -> 4

Graph is Connected

Dept. of CS&E , JSSATEB Page 70


Data Structures Laboratory Manual

LAB PROGRAM 12

Given a File of N employee records with a set K of Keys(4-digit) which uniquely determine
the records in file F. Assume that file F is maintained in memory by a Hash Table(HT) of m
memory locations with L as the set of memory addresses (2-digit) of locations in HT. Let
the keys in K and addresses in L are Integers. 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.

ABOUT THE EXPERIMENT:

A hash function usually means a function that compresses, meaning the output is shorter than the
input. Often, such a function takes an input of arbitrary or almost arbitrary length to one whose
length is a fixed number, like 160 bits. Hash functions are used in many parts of cryptography,
and there are many different types of hash functions, with differing security properties.

If keys are small integers, we can use an array to implement a symbol table, by interpreting the
key as an array index so that we can store the value associated with key i in array position i. In
this section, we consider hashing, an extension of this simple method that handles more
complicated types of keys. We reference key-value pairs using arrays by doing arithmetic
operations to transform keys into array indices.

Search algorithms that use hashing consist of two separate parts. The first step is to compute a
hash function that transforms the search key into an array index. Ideally, different keys would
map to different indices. This ideal is generally beyond our reach, so we have to face the
possibility that two or more different keys may hash to the same array index. Thus, the second
part of a hashing search is a collision-resolution process that deals with this situation.

Hash functions.
If we have an array that can hold M key-value pairs, then we need a function that can transform
any given key into an index into that array: an integer in the range [0, M-1]. We seek a hash
function that is both easy to compute and uniformly distributes the keys.
Typical example. Suppose that we have an application where the keys are U.S. social security
numbers. A social security number such as 123-45-6789 is a 9-digit number divided into three
fields. The first field identifies the geographical area where the number was issued (for example
number whose first field are 035 are from Rhode Island and numbers whose first field are 214
are from Maryland) and the other two fields identify the individual. There are a billion different
social security numbers, but suppose that our application will need to process just a few hundred
keys, so that we could use a hash table of size M = 1000. One possible approach to implementing
a hash function is to use three digits from the key. Using three digits from the field on the right is
likely to be preferable to using the three digits in the field on the left (since customers may not be
equally dispersed over geographic areas), but a better approach is to use all nine digits to make
an int value, then consider hash functions for integers, described next.
Positive integers. The most commonly used method for hashing integers is called modular

Dept. of CS&E , JSSATEB Page 71


Data Structures Laboratory Manual

hashing: we choose the array size M to be prime, and, for any positive integer key k, compute
the remainder when dividing k by M. This function is very easy to compute (k % M, in Java),
and is effective in dispersing the keys evenly between 0 and M-1.

PROGRAM CODE :

#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct employee
{
int id;
char name[15];
};
typedef struct employee EMP;
EMP emp[MAX];
int a[MAX];
int create(int num)
{
int key;
key = num % 100;
return key;
}
int getemp(EMP emp[],int key)
{
printf("\nEnter emp id: ");
scanf("%d",&emp[key].id);
printf("\nEnter emp name: ");
flushall();
gets(emp[key].name);
return key;
}
void display()
{
int i, ch;
printf("\n1.Display ALL\n2.Filtered Display");
printf("\nEnter the choice: ");
scanf("%d",&ch);
if(ch == 1)
{
printf("\nThe hash table is:\n");
printf("\nHTKey\tEmpID\tEmpName");
for(i=0; i<MAX; i++)
printf("\n%d\t%d\t%s", i, emp[i].id, emp[i].name);
}
else

Dept. of CS&E , JSSATEB Page 72


Data Structures Laboratory Manual

{
printf("\nThe hash table is:\n");
printf("\nHTKey\tEmpID\tEmpName");
for(i=0; i<MAX; i++)
if(a[i] != -1)
{
printf("\n%d\t%d\t%s", i, emp[i].id, emp[i].name);
continue;
}
}
}
void linear_prob(int key, int num)
{
int flag, i, count = 0;
flag = 0;
if(a[key] == -1)
{
a[key]=getemp(emp, key);
}
else
{
printf("\nCollision Detected...!!!\n");
i = 0;
while(i < MAX)
{
if (a[i] != -1)
count++;
else i++;
}
printf("\nCollision avoided successfully using LINEAR PROBING\n");
if(count == MAX)
{
printf("\n Hash table is full");
display(emp);
exit(1);
}
for(i=key; i<MAX; i++)
if(a[i] == -1)
{
a[i] = num;
flag = 1;
break;
}
i = 0;
while((i < key) && (flag == 0))
{

Dept. of CS&E , JSSATEB Page 73


Data Structures Laboratory Manual

if(a[i] == -1)
{
a[i] = num; flag=1;
break;
}
i++;
} // end while
} // end else
} // end linear_prob()
void main()
{
int num, key, i;
int ans = 1;
printf("\nCollision handling by linear probing: ");
for (i=0; i < MAX; i++)
{
a[i] = -1;
}
do
{
printf("\nEnter the data: ");
scanf("%d", &num);
key=create(num);
linear_prob(key,num);
printf("\nDo you wish to continue? (1/0): ");
scanf("%d",&ans);
}
while(ans);
display(emp);
}

Output:
RUN1:
Enter the data: 2
Enter emp id: 100
Enter emp name: Anand

Do you wish to continue?


(1/0): 1

Enter the data: 4


Enter emp id: 101
Enter emp name: Kumar
Do you wish to continue? (1/0): 0

1.Display ALL

Dept. of CS&E , JSSATEB Page 74


Data Structures Laboratory Manual

2.Filtered Display
Enter the choice: 1

The hash table is:


HTKey EmpID EmpName
0 0
1 0
2 100 anand
3 0
4 101 kumar
5 0
6 0
7 0
8 0
9 0

Dept. of CS&E , JSSATEB Page 75


Data Structures Laboratory Manual

Viva questions

1. What is data structure?


A data structure is a way of organizing data that considers not only the items stored, but also
their relationship to each other. Advance knowledge about the relationship between data items
allows designing of efficient algorithms for the manipulation of data.

2. List out the areas in which data structures are applied extensively?
1. Compiler Design,
2. Operating System,
3. Database Management System,
4. Statistical analysis package,
5. Numerical Analysis,
6. Graphics,
7. Artificial Intelligence,
8. Simulation

3. If you are using C language to implement the heterogeneous linked list, what pointer
type will you use?
The heterogeneous linked list contains different data types in its nodes and we need a link,
pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void
pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.

4. Minimum number of queues needed to implement the priority queue?


Two. One queue is used for actual storing of data and another for storing priorities.

1. Differentiate NULL and VOID.


Null is actually a value, whereas Void is a data type identifier. A variable that is given a Null
value simply indicates an empty value. Void is used to identify pointers as having no initial size.

6. What is the data structures used to perform recursion?


Stack. Because of its LIFO (Last In First Out) property it remembers its 'caller' so knows whom
to return when the function has to return. Recursion makes use of system stack for storing the
return addresses of the function calls. Every recursive function has its equivalent iterative (non-
recursive) function. Even when such equivalent iterative procedures are written, explicit stack is
to be used.

7. What are the notations used in Evaluation of Arithmetic Expressions using prefix and
postfix forms?
Polish and Reverse Polish notations.

8. Convert the expression ((A + B) * C - (D - E) ^ (F + G)) to equivalent Prefix and Postfix


notations.
1. Prefix Notation: ^ - * +ABC - DE + FG

Dept. of CS&E , JSSATEB Page 76


Data Structures Laboratory Manual

2. Postfix Notation: AB + C * DE - - FG + ^

9. Sorting is not possible by using which of the following methods? (Insertion, Selection,
Exchange, Deletion)
Sorting is not possible in Deletion. Using insertion we can perform insertion sort, using
selection
we can perform selection sort, using exchange we can perform the bubble sort (and other similar
sorting methods). But no sorting method can be done just using deletion.

10. What are the methods available in storing sequential files ?


1. Straight merging,
2. Natural merging,
3. Polyphase sort,
4. Distribution of Initial runs.

11. List out few of the Application of tree data-structure?


1. The manipulation of Arithmetic expression,
2. Symbol Table construction,
3. Syntax analysis.

12. List out few of the applications that make use of Multilinked Structures?
1. Sparse matrix,
2. Index generation.

13. In tree construction which is the suitable efficient data structure? (Array, Linked list,
Stack, Queue)
Linked list is the suitable efficient data structure.

14. What is the type of the algorithm used in solving the 8 Queens problem?
Backtracking.

15. In an AVL tree, at what condition the balancing is to be done?


If the 'pivotal value' (or the 'Height factor') is greater than 1 or less than -1.

16. What is the bucket size, when the overlapping and collision occur at same time?
One. If there is only one entry possible in the bucket, when the collision occurs, there is no way
to
accommodate the colliding value. This results in the overlapping of values.

17. Classify the Hashing Functions based on the various methods by which the key value is
found.
1. Direct method,
2. Subtraction method,
3. Modulo-Division method,
4. Digit-Extraction method,
5. Mid-Square method,

Dept. of CS&E , JSSATEB Page 77


Data Structures Laboratory Manual

6. Folding method,
7. Pseudo-random method.

18. What are the types of Collision Resolution Techniques and the methods used in each of
the type?
1. Open addressing (closed hashing), The methods used include: Overflow block.
2. Closed addressing (open hashing), The methods used include: Linked list, Binary tree.

19. In RDBMS, what is the efficient data structure used in the internal storage
representation?
B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching
easier. This corresponds to the records that shall be stored in leaf nodes.

20. What is a spanning Tree?


A spanning tree is a tree associated with a network. All the nodes of the graph appear on the
tree once. A minimum spanning tree is a spanning tree organized so that the total edge
weight between nodes is minimized.

21. Does the minimum spanning tree of a graph give the shortest distance between
any 2 specified nodes?
The Minimal spanning tree assures that the total weight of the tree is kept at its minimum.
But it doesn't mean that the distance between any two nodes involved in the minimumspanning
tree is minimum.

22. Which is the simplest file stru


cture? (Sequential, Indexed, Random)
Sequential is the simplest file structure.

23. Whether Linked List is linear or Non-linear data structure?


According to Access strategies Linked list is a linear one.
According to Storage Linked List is a Non-linear one.

24. Differentiate file structure from storage structure.


Basically, the key difference is the memory area that is being accessed. When dealing with the
structure that resides the main memory of the computer system, this is referred to as storage
structure. When dealing with an auxiliary structure, we refer to it as file structures.

25. What is a linked list?


A linked list is a sequence of nodes in which each node is connected to the node following it.
This forms a chain-like link of data storage.

26. How do you reference all the elements in a one-dimension array?


To do this, an indexed loop is used, such that the counter runs from 0 to the array size minus one.
In this manner, we are able to reference all the elements in sequence by using the loop counter as
the array subscript.

Dept. of CS&E , JSSATEB Page 78


Data Structures Laboratory Manual

27. In what areas do data structures applied?


Data structures is important in almost every aspect where data is involved. In general, algorithms
that involve efficient data structure is applied in the following areas: numerical analysis,
operating system, A.I., compiler design, database management, graphics, and statistical analysis,
to name a few.

28. What is LIFO?


LIFO is short for Last In First Out, and refers to how data is accessed, stored and retrieved.
Using this scheme, data that was stored last , should be the one to be extracted first. This also
means that in order to gain access to the first data, all the other data that was stored before this
first data must first be retrieved and extracted.

29. Explain Binary Search Tree


A binary search tree stores data in such a way that they can be retrieved very efficiently. The left
subtree contains nodes whose keys are less than the node’s key value, while the right subtree
contains nodes whose keys are greater than or equal to the node’s key value. Moreover, both
subtrees are also binary search trees.

30. Are linked lists considered linear or non-linear data structures?


It actually depends on where you intend to apply linked lists. If you based it on storage, a linked
list is considered non-linear. On the other hand, if you based it on access strategies, then a linked
list is considered linear.

31. What is the primary advantage of a linked list?


A linked list is a very ideal data structure because it can be modified easily. This means that
modifying a linked list works regardless of how many elements are in the list.

32. What is the difference between a PUSH and a POP?


Pushing and popping applies to the way data is stored and retrieved in a stack. A push denotes
data being added to it, meaning data is being “pushed” into the stack. On the other hand, a pop
denotes data retrieval, and in particular refers to the topmost data being accessed.

33. What is a linear search?


A linear search refers to the way a target key is being searched in a sequential data structure.
Using this method, each element in the list is checked and compared against the target key, and
is repeated until found or if the end of the list has been reached.

33. How does variable declaration affect memory allocation?


The amount of memory to be allocated or reserved would depend on the data type of the variable
being declared. For example, if a variable is declared to be of integer type, then 32 bits of
memory storage will be reserved for that variable.

34. What is the advantage of the heap over a stack?

Dept. of CS&E , JSSATEB Page 79


Data Structures Laboratory Manual

Basically, the heap is more flexible than the stack. That’s because memory space for the heap
can be dynamically allocated and de-allocated as needed. However, memory of the heap can at
times be slower when compared to that stack.

35. What is a postfix expression?


A postfix expression is an expression in which each operator follows its operands. The
advantage of this form is that there is no need to group sub-expressions in parentheses or to
consider operator precedence.

36. What is the difference between the HEAP and the STACK?
HEAP is used to store dynamically allocated memory (malloc). STACK stores static data (int,
const)

37. Where in memory are HEAP and the STACK located relative to the executing
program?
The STACK and HEAP are stored "below" the executing program. The HEAP "grows" toward
the program executable while the STACK grows away from it.
38. Describe the data structures of a double-linked list
A double-linked list structure contains one pointer to the previous record in the list and a pointer
to the next record in the list plus the record data.

39. How do you insert a record between two nodes in double-linked list?
Previous R; Data R; Next R; To insert a record (B) between two others (A and C): Previous.B =
A; Next.B = C; Next.A = B; Previous.C = B;

40. Define a linear and non linear data structure. Linear data structure
A linear data structure traverses the data elements sequentially, in which only one data element
can directly be reached.
Ex: Arrays, Linked Lists
Non-Linear data structure: Every data item is attached to several other data items in a way that is
specific for reflecting relationships. The data items are not arranged in a sequential structure.
Ex: Trees, Graphs

Dept. of CS&E , JSSATEB Page 80

Das könnte Ihnen auch gefallen