Vous êtes sur la page 1sur 174

INDERPRASTHA ENGINEERING COLLEGE

GHAZIABAD

COMPUTER SC. & ENGINEERING DEPARTMENT

LAB MANUAL
DATA STRUCTURE LAB
TCS-352
(B.TECH. - 3 SEMESTER)
RD

INDEX
1. PROGRAMS BASED ON RECURSION.
2. PROGRAMS BASED ON STRINGS.
3. PROGRAMS BASED ON ARRAYS.
4. PROGRAMS BASED ON STACK.
5. PROGRAMS BASED ON QUEUES.
6. PROGRAMS BASED ON LINKED LIST.
7. IMPLEMENT THE VARIOUS SEARCHING ALGORITHMS
8. IMPLEMENTATION OF VARIOUS SORTING ALGORITHMS
9. PROGRAM BASED ON BINARY TREES.
10. PROGRAMS BASED ON GRAPH.
11. PROGRAMS BASED ON SIMULATION OF HASHING
12. PROGRAMS BASED ON SPARSE MATRIX

NOTE: 1-10 ARE AS PER THE UPTU SYLLABUS AND 11 & 12 ARE BEYOND THE SYLLABUS

DATA STRUCTURE LAB (ECS - 352)


LIST OF PROGRAMS
1. PROGRAMS BASED ON RECURSION
I.
II.
III.
IV.
V.
VI.

PROGRAM FOR CALCULATION OF FACTORIAL OF THE GIVEN NUMBER.


PROGRAM FOR FINDING NTH FIBONACCI NUMBER AND ANALYZING ITS RUN TIME
PROGRAM FOR FINDING NTH FIBONACCI NUMBER USING ARRAY
PROGRAM FOR BINARY SEARCH
PROGRAM FOR TOWERS OF HANOI
PROGRAM FOR NATURAL NUMBER MULTIPLICATION

2. PROGRAMS BASED ON STRINGS.


I.
II.
III.
IV.

WRITE A PROGRAM TO INPUT A STRING AND CALCULATE THE LENGTH OF THE STRING
WRITE A PROGRAM TO COPY ONE STRING TO ANOTHER.
WRITE A PROGRAM TO CONCATENATE TWO STRINGS.
WRITE A PROGRAM TO ACCEPT A STRING AND CONVERT ALL THE CHARACTERS OF THE
UPPERCASE.
V. WRITE A PROGRAM TO PRINT A STRING IN ALPHABETICAL ORDER.
VI. WRITE A PROGRAM TO COMPARE TWO STRINGS
VII. WRITE A PROGRAM FOR PATTERN MATCHING

STRING FROM LOWERCASE TO

3. PROGRAMS BASED ON ARRAYS.


I. PROGRAM FOR INSERTION OF AN ELEMENT AT SPECIFIED LOCATION IN THE ARRAY
II. PROGRAM FOR DELETION OF AN ELEMENT FROM THE SPECIFIED LOCATION IN THE ARRAY
III. PROGRAM FOR DELETION OF ALL OCCURANCES OF X FROM THE ARRAY

4. PROGRAMS BASED ON STACKS.


I. WRITE A MENU DRIVEN PROGRAM TO IMPLEMENT THE PUSH, POP AND DISPLAY OPTION OF THE STACK WITH THE HELP
OF STATIC MEMORY ALLOCATION.
II. WRITE A MENU DRIVEN PROGRAM TO IMPLEMENT THE PUSH, POP AND DISPLAY OPTION OF THE STACK WITH THE HELP
OF DYNAMIC MEMORY ALLOCATION.
III. WRITE A PROGRAM TO CONVERT A INFIX EXPRESSION TO POSTFIX EXPRESSION.
IV. WRITE A PROGRAM TO CONVERT A INFIX EXPRESSION TO PREFIX EXPRESSION.
V. WRITE A PROGRAM TO EVALUATE THE GIVEN POSTFIX EXPRESSION.
VI. PROGRAM TO CHECK THE VALIDITY OF THE GIVEN EXPRESSION BASED ON THE PARENTHESIS
VII. PROGRAM TO CHECK THE VALIDITY OF THE GIVEN EXPRESSION BASED ON THE BRACKETS
VIII. PROGRAM TO CHECK IF THE GIVEN STRING IS PALINDROME USING STACKS
IX. SIMULATION OF TWO STACKS ON A SINGLE ARRAY

5. PROGRAMS BASED ON QUEUES.


I. WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS OPERATIONS ON A LINEAR QUEUE WITH THE HELP OF
STATIC MEMORY ALLOCATION.
II. WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS OPERATIONS ON A LINEAR QUEUE WITH THE HELP OF
DYNAMIC MEMORY ALLOCATION.
III. WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS OPERATIONS ON A CIRCULAR QUEUE WITH THE HELP
OF STATIC MEMORY ALLOCATION.
IV. WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS OPERATIONS ON A DEQUEUE QUEUE WITH
THE HELP OF STATIC MEMORY ALLOCATION.
V. WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS OPERATIONS ON A PRIORITY QUEUE WITH THE
HELP OF STATIC MEMORY ALLOCATION.
VI. SIMULATION OF AIR TRAFFIC CONTROL SYSTEM

6. PROGRAMS BASED ON LINKED LIST.


I. WRITE A MENU DRIVEN PROGRAM TO IMPLEMEN VARIOUS OPERATIONS ON A LINEAR LINKED LIST.
II. WRITE A MENU DRIVEN PROG TO IMPLEMENT VARIOUS OPERATIONS ON A CIRCULAR LINKED LIST
III. WRITE A FUNCTION TO CONCATENATE TWO LINEAR LINKED LIST.

IV. WRITE A MENU DRIVEN PROG TO IMPLEMENT VARIOUS OPERATIONS ON A DOUBLY LINKED LIST
V. PROGRAM FOR ADDITION OF TWO POLYNOMIALS
VI. PROGRAM FOR ADDITION OF VERY LONG INTEGER NUMBERS (STORAGE OF THESE NUMBERS
INT OR LONG INT)
VII. PROGRAM FOR CONCATENATION OF TWO CIRCULARLINKED LISTS
VIII. PROGRAM FOR CREATING ANOTHER COPY OF THE LINKED LIST
IX. PROGRAM FOR SPLITTING THE GIVEN LINKED LIST.
X. PROGRAM FOR MERGING TWO ORDERED LINKED LISTS
XI. PROGRAM FOR INSERTION OF A NO IN THE GIVEN ORDERED LINKED LIST
XII. PROGRAM FOR DELETION OF ALL THE OCCURANCES OF X FROM LINKED LIST
XIII. PROGRAM FOR CONCATENATION OF TWO CIRCULAR LINKED LISTS
XIV. PROGRAM FOR IMPLEMENTATION OF JOSEPHUS PROBLEM

IS NOT POSSIBLE IN

7. PROGRAMS BASED ON SEARCHING ALGORITHMS.


I. WRITE

A PROGRAM TO INPUT HOW MANY NUMBERS AND THEN INPUT THE NUMBERS AND THEN SEARCH ANY NUMBER

WITH THE HELP OF SEQUENTIAL/LINEAR SEARCH.

II. WRITE

A PROGRAM TO INPUT HOW MANY NUMBERS AND THEN INPUT THE NUMBERS AND THEN SEARCH ANY NUMBER

WITH THE HELP OF

III. WRITE

BINARY SEARCH.

A PROGRAM TO INPUT HOW MANY NUMBERS AND THEN INPUT THE NUMBERS AND THEN SEARCH ANY

NUMBER WITH THE HELP OF INDEX

SEQUENTIAL SEARCH

8. PROGRAMS BASED ON SORTING ALGORITHMS.


BUBBLE SORT
HEAP SORT.

SELECTION SORT INSERTION SORT MERGE SORT


RADIX SORT
SHELL SORT

QUICK SORT

9. PROGRAMS BASED ON BINARY TREES.


I. PROGRAM FOR CREATION OF BINARY TREE
II. WRITE A MENU DRIVEN PROGRAM TO IMPLEMENT VARIOUS TRAVERSAL OPERATIONS IN A BINARY TREE.
III. WRITE A MENU DRIVEN PROGRAM TO IMPLEMENT VARIOUS OPERATIONS ON A BINARY SEARCH TREE (MINIMUM,
MAXIMUM, INSERTION, TRAVERSAL & DELETION).
IV. WRITE A PROGRAM TO FIND THE LOGICAL SUCCESSOR OF A NODE IN A BINARY SEARCH TREE
V. PROGRAM FOR GENERATION OF HUFFMAN CODES
VI. PROGRAM FOR COUNTING THE NUMBER OF NODES IN THE BINARY TREE
VII. PROGRAM FOR FINDING THE HEIGHT OF THE GIVEN BINARY TREE
VIII. PROGRAM FOR FINDING THE BALANCE OF EVERY NODE IN THE BINARY TREE
IX. PROGRAM FOR CREATION OF GENERAL TREE AND CONVERSION OF THE SAME TO BINARY TREE

10. PROGRAMS BASED ON GRAPHS.


I.
II.
III.
IV.

WRITE A C PROGRAM FOR DEPTH FIRST SEARCH OF A GRAPH.


WRITE A C PROGRAM FOR BREADTH FIRST SEARCH OF A GRAPH.
WRITE A C PROGRAM FOR WARSHALLS ALGORITHM FOR SHORTEST PATH
WRITE A C PROGRAM FOR WARSHALLS ALGORITHM FOR TRANSITIVE CLOSURE

11. PROGRAMS BASED ON SPARSE MATRIX.


I. PROGRAM FOR ADDITION OF TWO SPARSE MATRIX.
II. PROGRAM FOR SUBSTRACTION OF TWO SPARSE MATRIX.
III. PROGRAM FOR FINDING TRANSPOSE OF THE GIVEN SPARSE MATRIX.

12. PROGRAMS BASED ON HASHING


SIMULATION OF HASHING ON THE ARRAY/ CALCUTAION OF HASH ADDRESSES BASED ON THE ARRAY SIZE FURTHER OPEN
ADDRESSING AND COLLISION RESOLUTION BY LINEAR PROBING.

NOTE: THE PRGRAMS IN ITALICS FONT ARE BEYOND THE SYLLABUS


4

ASSIGNMENT NO. 1
OBJECT: PROGRAMS BASED ON RECURSION.
THEORY AND CONCEPTS
THE

FUNCTION WHICH IS CALLED BY ITSELF IS CALLED RECURSIVE FUNCTION AND THIS PROCESS IS KNOWN AS RECURSION.

MAIN ADVANTAGE OF RECURSION IS THAT WE DIVIDE AND THEN CONQUER THE PROBLEMS WITH THE HELP OF RECURSION.

THE
THE

LIMITATION OF USING THE RECURSION IS THAT WE CAN ONLY CREATE THOSE PROGRAMS WITH THE HELP OF RECURSION IN WHICH
THE NEXT STEP DEPENDS UPON THE PREVIOUS STEP.

PROBLEMS
VII. PROGRAM FOR CALCULATION OF FACTORIAL OF THE GIVEN NUMBER.
VIII. PROGRAM FOR FINDING NTH FIBONACCI NUMBER
IX. PROGRAM FOR BINARY SEARCH
X. PROGRAM FOR TOWERS OF HANOI
XI. PROGRAM FOR NATURAL NUMBER MULTIPLICATION

/****************************************************************/
/* Prog for Finding factorial of a number using recursion
*/
/****************************************************************/
/* Function Prototyping */
int factorial(int);
/****************************************************************/
void main()
{
int n,fact;
clrscr();
printf("enter the number ");
scanf("%d",&n);
fact=factorial(n);
printf("The factorial of the given number is:=>\t%d",fact);
getch();
}
/****************************************************************/
/*********************** Function Definitions *****************/
/****************************************************************/
int factorial(int n)
{
if(n==0)
return 1;
else
return(n*factorial(n-1));
}
/****************************************************************/

Output:
Enter the number
5
Factorial of the given number is:=> 120

/****************************************************************/
/**** Prog for finding nth Fibonacci number using recursion and analyzing its run time *****/
/*** Des: The program has ambiguous recursive calls for the same no. found in between **/
/****************************************************************/
/****************** Pre-processoer directives *******************/
/****************************************************************/
#include<time.h>
#include<stdlib.h>
/****************************************************************/
/***************** Function prototyping *************************/
/****************************************************************/
long int fib(long int );
/****************************************************************/
void main()
{
long int n,f;
time_t t1,t2;
clrscr();
scanf("%ld",&n);
t1=time(NULL);
f=fib(n);
t2=time(NULL);
printf("\n\n%ld",f);
printf("\nTime elapsed is%ld",t2-t1);
getch();
}
/****************************************************************/
/***************** Function Definitions *************************/
/****************************************************************/
long int fib(long int n)
{
if(n==1||n==2)
return 1;
else
return(fib(n-1)+fib(n-2));
}
/****************************************************************/

Output

/****************************************************************/
/* Prog for finding nth Fibonacci number & analyzing its run time */
/* By: Akhilesh Kumar Srivastava */
/* Des: The Use of Array finds the significant improvement in run time and
does not make the repeatative calls */
/****************************************************************/
/******************* Pre-processoer directives ************************/
/****************************************************************/
#include<time.h>
#include<stdlib.h>
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
long int fib(long int);
/************ Global declaration of Arrays ****************************/
long int a[100];
/****************************************************************/
void main()
{
long int n,f;
time_t t1,t2;
clrscr();
scanf("%ld",&n);
t1=time(NULL);
f=fib(n);
t2=time(NULL);
printf("\n\n%ld",f);
printf("\nTime elapsed is%ld",t2-t1);
getch();
}
/****************************************************************/
/********************** Function Definitions ************************/
/****************************************************************/
long int fib(long int n)
{
if(n==1||n==2)
{ a[n]=1; return 1;}
else
{
if(a[n]==0)
{
a[n]=(fib(n-1)+fib(n-2));
}
return(a[n]);
}
}
/****************************************************************/

Output

10

/****************************************************************/
/* Program for Binary Search recursively */
/* By: Akhilesh Kumar Srivastava
*/
/* Des: This is O(logn) Algo average case and O(1) in Best case */
/****************************************************************/
#include<stdio.h>
#include<conio.h>
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
int binary_search(int[],int,int,int);
/****************************************************************/
void main()
{
int a[10]={2,4,6,8,10,12,14,16,18,20};
int x,n,y;
clrscr();
printf("Enter the element to be searched");
scanf("%d",&x);
y=binary_search(a,0,9,x);
if(y==-1)
printf("\nThe element is not present in the array");
else
printf("\nThe element is present at %d location in the array",y+1);
getch();
}
/****************************************************************/
/* Function Definition */
/****************************************************************/
int binary_search(int a[],int low,int high,int x)
{
int mid;
if(low>high)
return -1;
mid=(low+high)/2;
if(a[mid]==x)
return mid;
else
{
if(x<a[mid])
binary_search(a,low,mid-1,x);
else
binary_search(a,mid+1,high,x);
}
}
/****************************************************************/

Output:
11

12

/****************************************************************/
/* Prog for Towers of Hanoi Problem with 3 toweres & n disks */
/* By: Akhilesh Kumar Srivastava */
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void tow_of_hanoi(int,int,int,int);
/****************************************************************/
void main()
{
int n;
clrscr();
printf("Enter two number of disks");
scanf("%d",&n);
tow_of_hanoi(n,1,2,3);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
void tow_of_hanoi(int n,int A,int B,int C)
{
if(n>=1)
{
tow_of_hanoi(n-1,A,C,B);
printf("\nTransfer disk from \t%d\t to \t%d\t",A,B);
tow_of_hanoi(n-1,C,B,A);
}
}
/****************************************************************/
Output:->
----------Enter two number of disks3
Transfer disk from
1
to
2
Transfer disk from
1
to
3
Transfer disk from
2
to
3
Transfer disk from
1
to
2
Transfer disk from
3
to
1
Transfer disk from
3
to
2
Transfer disk from
1
to
2
-------------------------------------------Enter two number of disks4
Transfer disk from
1
to
3
Transfer disk from
1
to
2
Transfer disk from
3
to
2
Transfer disk from
1
to
3
Transfer disk from
2
to
1
Transfer disk from
2
to
3
Transfer disk from
1
to
3
Transfer disk from
1
to
2
Transfer disk from
3
to
2
Transfer disk from
3
to
1
Transfer disk from
2
to
1
Transfer disk from
3
to
2
Transfer disk from
1
to
3
Transfer disk from
1
to
2
Transfer disk from
3
to
2
-------------------------------------------

13

Enter two number of disks5


Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer
Transfer

disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk
disk

from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from
from

1
1
2
1
3
3
1
1
2
2
3
2
1
1
2
1
3
3
1
3
2
2
3
3
1
1
2
1
3
3
1

to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to
to

2
3
3
2
1
2
2
3
3
1
1
3
2
3
3
2
1
2
2
1
3
1
1
2
2
3
3
2
1
2
2

14

/****************************************************************/
/******* Prog for Natural Number multiplication using recursion ********/
/*** By: Akhilesh Kumar Srivastava ***/
/****************************************************************/
/****************************************************************/
/***************** Function prototyping *************************/
/****************************************************************/
int natural_mul(int,int);
/****************************************************************/
void main()
{
int a,b,c;
clrscr();
printf("Enter the first no:=>\t");
scanf("%d",&a);
printf("Enter the second no:=>\t");
scanf("%d",&b);
c=natural_mul(a,b);
printf("\n%d",c);
getch();
}
/****************************************************************/
/***************** Function defintion ***************************/
/****************************************************************/
int natural_mul(int x,int y)
{
if(y==1)
return x;
else
return (x+natural_mul(x,y-1));
}
/****************************************************************/

Output

15

ASSIGNMENT NO. 2
OBJECT: - PROGRAMS BASED ON STRINGS.
VIII. WRITE A PROGRAM TO INPUT A STRING AND CALCULATE THE LENGTH OF THE STRING WITHOUT USING LIBRARY
FUNCTIONS.
IX. WRITE A PROGRAM TO COPY ONE STRING TO ANOTHER WITHOUT USING LIBRARY FUNCTIONS.
X. WRITE A PROGRAM TO CONCATENATE TWO STRINGS.
XI. WRITE A PROGRAM TO ACCEPT A STRING AND CONVERT ALL THE CHARACTERS OF THE STRING FROM
LOWERCASE TO UPPERCASE .
XII. WRITE A PROGRAM TO PRINT A STRING IN ALPHABETICAL ORDER.
XIII. WRITE A PROGRAM TO COMPARE TWO STRINGS WITHOUT USING LIBRARY FUNCTIONS.
XIV. WRITE A PROGRAM FOR PATTERN MATCHING

16

/************************************************************/
/******** PROGRAM FOR FINDING THE LENGTH OF THE STRING ********/
/******** BY: AKHILESH SRIVASTAVA
**************/
/******** DES: THE STRING MAY NOT INCLUDE SPACES IN BETWEEN *******/
/************************************************************/
void main()
{
char s[25];
int i=0;
clrscr();
printf("Enter the string:=>\t");
scanf("%s",s);
while(s[i]!='\0')
i++;
printf("Length of the string is:=> %d",i);
getch();
}
/************************************************************/

OUTPUT:
Enter the string:=> akhileshsrivastava
Length of the string is:=> 18

Enter the string:=> inderprastha


Length of the string is:=> 12

17

/************************************************************/
/******** PROGRAM FOR FINDING THE LENGTH OF THE STRING ********/
/******** BY: PUNEET SHAH
**************/
/******** DES: THE STRING MAY INCLUDE SPACES IN BETWEEN *******/
/************************************************************/
void main()
{
char s[25];
int i=0;
clrscr();
printf("Enter the string:=>\t");
scanf("%[^\n]",s);
while(s[i]!='\0')
i++;
printf("Length of the string is:=> %d",i);
getch();
}
/************************************************************/

Output:
Enter the string:=> akhilesh srivastava
Length of the string is:=> 19
Enter the string:=> Engineering College Bikaner
Length of the string is:=> 27

18

/******************************************************************/
/***** PROG FOR CONVERSION OF UPPERCASE CHARACTERS TO LOWERCASE IN THE STRING *****/
/******** BY: AKHILESH SRIVASTAVA
**************************/
/******************************************************************/
void main()
{
char s[25];
int i=0;
clrscr();
printf("Enter the string:=>\t");
scanf("%s",s);
while(s[i]!='\0')
{
s[i]=s[i]+32; i++;
}
printf("\nThe result string is:=> %s",s);
getch();
}
/************************************************************/

Output:
Enter the string:=>

MYNAME

The Result string is :=> myname

Enter the string:=>

INDERPRASTHA

The Result string is :=> inderprastha

19

/******************************************************************/
/****** PROG FOR CONVERSION OF LOWERCASE CHARACTERS TO UPPERCASE IN THE STRING ******/
/******** BY: AKHILESH SRIVASTAVA
**************************/
/******************************************************************/
void main()
{
char s[25];
int i=0;
clrscr();
printf("Enter the string:=>\t");
scanf("%s",s);
while(s[i]!='\0')
{
s[i]=s[i]-32; i++;
}
printf("\nThe result string is:=> %s",s);
getch();
}
/************************************************************/

Output:
Enter the string:=>

myname

The Result string is :=> MYNAME

Enter the string:=>

inderprastha

The Result string is :=> INDERPRASTHA

20

/********************************************************************/
/*********** PROG FOR CONCATENATION OF TWO STRINGS ******************/
/******** BY: AKHILESH SRIVASTAVA
***************************/
/*******************************************************************/
void main()
{
char s1[25],s2[25],d[50];
int i=0,j=0;
clrscr();
printf("Enter the first string:=>\t");
scanf("%s",s1);
printf("Enter the second string:=>\t");
scanf("%s",s2);
while(s1[i]!='\0')
{
d[i]=s1[i];
i++;
}
while(s2[j]!='\0')
{
d[i]=s2[j];
i++; j++;
}
d[i]='\0';
printf("\nThe Concatenated string is:=> %s",d);
getch();
}
/************************************************************/

Output
Enter the first string:=>
amit
Enter the second string:=> abh
The Concatenated string is:=> amitabh

ENTER THE FIRST STRING:=>


ENTER THE SECOND STRING:=>

ENGINE
ERING

THE CONCATENATED STRING IS:=> ENGINEERING

21

/******************************************************************/
/********** PROG FOR COMARISION OF TWO STRINGS *********************/
/******** BY: AKHILESH SRIVASTAVA
**************************/
/******************************************************************/
void main()
{
char s1[25],s2[25],t;
int i=0,j,l1=0,l2=0;
clrscr();
printf("Enter the first string:=>\t");
scanf("%s",s1);
printf("Enter the second string:=>\t");
scanf("%s",s2);
while(s1[l1]!='\0')
l1++;
while(s2[l2]!='\0')
l2++;
if(l1>l2)
printf("\nFirst String is larger than the second one");
else
{
if(l1<l2)
printf("\nSecond String is larger than the first one");
else
{
while(s1[i]!='\0')
{ if(s1[i]==s2[i])
i++;
else
break;
}
if(i==l1)
printf("\nStrings are same");
else
printf("\nStrings are different");
}
}
getch();
}
/************************************************************/

22

Output
Enter the first string:=>
akhilesh
Enter the second string:=> akhilesh
Strings are same

Enter the first string:=>


akhilesh
Enter the second string:=> kumar
First String is larger than the second one

Enter the first string:=>


myname
Enter the second string:=> engineering
Second String is larger than the first one

23

/*******************************************************************/
/*********** PROG FOR COPYING ONE STRING TO THE OTHER ***************/
/************ BY: AKHILESH SRIVASTAVA
**********************/
/******************************************************************/
void main()
{
char s[25],d[25];
int i=0;
clrscr();
printf("Enter the source string:=>\t");
scanf("%s",s);
printf("Enter the destination string:=>\t");
scanf("%s",d);
while(s[i]!='\0')
{
d[i]=s[i];
i++;
}
d[i]='\0';
printf("\nThe source string is:=> %s",s);
printf("\nThe destination string is:=> %s",d);
getch();
}
/************************************************************/

OUTPUT
Enter the source string:=> akhilesh
Enter the destination string:=> kumar
The source string is:=> akhilesh
The destination string is:=> akhilesh

24

/******************************************************************/
/********** PROG FOR PRINTING A STRING IN THE ALPHABETICAL ORDER *****/
/************* BY: AKHILESH SRIVASTAVA
*********************/
/******************************************************************/
void main()
{
char s[25],t;
int i,j,l=0;
clrscr();
printf("Enter the string:=>\t");
scanf("%s",s);
while(s[l]!='\0')
l++;
for(i=0;i<l-1;i++)
{
for(j=i+1;j<l;j++)
{
if(s[j]<s[i])
{
t=s[i];
s[i]=s[j];
s[j]=t;
}
}
}
printf("\nThe sorted string is:=> %s",s);
getch();
}
/************************************************************/

OUTPUT
Enter the string:=>

inderprastha

The sorted string is:=> aadehinprrst

25

/*****************************************************************/
/*********** Prog for String Pattern matching ************************/
/*********** By: Akhilesh Kumar Srivastava *************************/
/****************************************************************/
/****************** Pre-processoer directives *******************/
/****************************************************************/
#include<stdio.h>
#include<conio.h>
#include<string.h>
/****************************************************************/
/***************** Function prototyping *************************/
/****************************************************************/
int xstrsearch(char s1[],char s2[]);
/****************************************************************/
void main()
{
clrscr();
char s1[30];
char s2[10];
printf("\nEnter the first string:=>\t");
scanf("%s",s1);
printf("\nEnter the second string:=>\t");
scanf("%s",s2);
int pos;
pos=xstrsearch(s1,s2);
if(pos<0)
{
printf("\npattern dose not match");
}
else
{
printf("pattern is matching %d",pos);
}
getch();
}
/****************************************************************/
/***************** Function Definitions *************************/
/****************************************************************/
int xstrsearch(char s1[],char s2[])
{
int i,j,k;
int len1=strlen(s1);
int len2=strlen(s2);
for(i=0;i<(len1); i++)
{
j=0;
k=i;
printf("s1-k=%c,s2-j=%c\n",s1[k],s2[j]);
26

while(s1[k]==s2[j]&&j<len2)
{
printf("matching from .....s1-k=%c,s2-j=%c\n",s1[k],s2[j]);
j++;
k++;
}
if(j==len2)
{
return(i);
}
}
return(-1);
}
/****************************************************************/

OUTPUT
Enter the first string:=>

engineeringcollege

Enter the second string:=> college


s1-k=e,s2-j=c
s1-k=n,s2-j=c
s1-k=g,s2-j=c
s1-k=i,s2-j=c
s1-k=n,s2-j=c
s1-k=e,s2-j=c
s1-k=e,s2-j=c
s1-k=r,s2-j=c
s1-k=i,s2-j=c
s1-k=n,s2-j=c
s1-k=g,s2-j=c
s1-k=c,s2-j=c
matching from .....s1-k=c,s2-j=c
matching from .....s1-k=o,s2-j=o
matching from .....s1-k=l,s2-j=l
matching from .....s1-k=l,s2-j=l
matching from .....s1-k=e,s2-j=e
matching from .....s1-k=g,s2-j=g
matching from .....s1-k=e,s2-j=e
pattern is matching 11

27

ASSIGNMENT NO. 3
OBJECT:- PROGRAMS BASED ON ARRAYS.
THEORY AND CONCEPTS:ARRAY PLAYS A VERY IMPORTANT ROLE IN C LANGUAGE. WHEN WE STORE THE VARIOUS NUMBERS OF THE SAME DATA
TYPE THEN WE HAVE TO USE THE CONCEPT OF ARRAY. SO WE CAN SAY THAT ARRAY IS THE COLLECTION OF SAME DATA
TYPE.
ARRAY IS CLASSIFIED INTO FOLLOWING CATEGORIES:1->SINGLE DIMENSION ARRAY

2->DOUBLE DIMENSION ARRAY

1-> SINGLE DIMENSION ARRAY:- SINGLE DIMENSION ARRAY IS USED TO STORE THE SAME DATA TYPE NUMBERS.
THE SYNTAX FOR DEFINING THE SINGLE DIMENSIONAL ARRAY IS AS FOLLOWS:<DATA TYPE><ARRAY NAME>[SIZE];
FOR EXAMPLE IF WE DEFINE
INT A[5]; THIS MEANS A IS AN ARRAY OF 5 INTEGERS AND 10 BYTES MEMORY IS ALLOCATED FOR A. THE FIRST
ELEMENT IS STORED AT THE POSITION OF A[0] AND 5 ELEMENT IS STORED AT THE POSITION OF A[4].
TH

2-> DOUBLE DIMENSION ARRAY:- DOUBLE DIMENSION ARRAY IS USED TO STORE THE SAME DATA TYPE NUMBERS IN
MATRIX FORM.
THE SYNTAX FOR DEFINING THE SINGLE DIMENSIONAL ARRAY IS AS FOLLOWS:<DATA TYPE><ARRAY NAME>[SIZE OF ROW][SIZE OF COLUMN];
FOR EXAMPLE IF WE DEFINE
INT A[3][3]; THIS MEANS A IS AN ARRAY OF 3 ROWS AND 3 COLUMNS. THE FIRST ELEMENT IS STORED AT THE
POSITION OF A[0][0] AND THE LAST ELEMENT IS STORED AT THE POSITION OF A[2][2].
PROBLEMS :IV. PROGRAM FOR INSERTION OF AN ELEMENT AT SPECIFIED LOCATION IN THE ARRAY
V. PROGRAM FOR DELETION OF AN ELEMENT FROM THE SPECIFIED LOCATION IN THE ARRAY

28

/****************************************************************/
/* PROG FOR ARRAY INSERTION, DELETION, TRAVERSAL*/
/* BY: AKHILESH KUMAR SRIVASTAVA */
/****************************************************************/
#include<stdio.h>
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void insert(int,int);
int remov(int);
void traverse();
/****************************************************************/
int a[20]={5,8,2,3,1,9,7};
int n=7;
/****************************************************************/
void main()
{
int x,y;
char ch,c;
clrscr();
printf("The array is=>\n");
traverse(n);
start:
printf("\n\n\n1. Insertion in the array\n");
printf("2. Removal from the array\n");
printf("3. Traversal the array\n");
printf("4. exit\n");
printf("===========================\n");
printf("Enter your choice\t");
scanf("%d",&c);
switch(c)
{
case 1: printf("\nEnter the element to be inserted");
scanf("%d",&x);
printf("\nEnter the location where to insert");
scanf("%d",&y);
insert(x,y);
printf("\nThe array is:=>\n");
traverse();
break;
case 2: printf("\nEnter the location from where to remov");
scanf("%d",&y);
x=remov(y);
printf("\nRemoved item is:=> \t%d",x);
printf("\nThe array is:=>\n");
traverse();
break;
29

case 3: printf("\nThe array is:=>\n");


traverse(); break;
case 4: exit(1);
default: printf("\nWrong choice"); break;
}
printf("\n\nDo you wish to continue? (y/n) ");
fflush(stdin);
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
goto start;
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
void insert(int x,int y)
{
int i;
for(i=n-1;i>=y;i--)
a[i+1]=a[i];
a[y]=x;
n=n+1;
}
/****************************************************************/
int remov(int y)
{
int i,x;
x=a[y];
for(i=y;i<n;i++)
a[i]=a[i+1];
n=n-1;
return x;
}
/****************************************************************/
void traverse()
{
int i;
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
/****************************************************************/

30

OUTPUT
The array is=>
5
8
2
3

1. Insertion in the array


2. Removal from the array
3. Traversal the array
4. exit
===========================
Enter your choice
1
Enter the element to be inserted43
Enter the location where to insert3
The array is:=>
5
8
2
43

Do you wish to continue? (y/n) y

1. Insertion in the array


2. Removal from the array
3. Traversal the array
4. exit
===========================
Enter your choice
2
Enter the location from where to remov6
Removed item is:=>
The array is:=>
5
8
2
43

9
3

Do you wish to continue? (y/n)

31

/****************************************************************/
/*TO DELETE ALL THE OCCURENCES OF ANY NUMBER IN AN ARRAY*/
/*BY - VAIBHAV VERMA */
/* CSE Second Year Third Semester */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
#include<conio.h>
/****************************************************************/
/********************** Function Definition *********************/
/****************************************************************/
void delet(int a,int z[100],int j)
{
int b=0,c,d,e,i;
while(b<j)
{
if(z[b]==a)
{
for(c=b;c<j;c++)
{
z[c]=z[c+1];
}
j--;
}
else
b++;
}
printf("\n\nafter detetion %d the list is =",a);
for(i=0;i<j;i++)
{
printf("%d,",z[i]);
}
}
/*******************************************************************/
void main()
{
int a,z[100],j,i,b,c,d;
char w;
clrscr();
printf("\n\n
****TO DELET AL THE OCCURENCES****
");
printf("\n\n****************************************************************");
do
{
printf("\n\nEnter totl no. = ");
scanf("%d",&j);
for(i=0;i<j;i++)
{
printf("\n\nEnter no =");
scanf("%d",&z[i]);
32

}
printf("\n\nU have enter =");
for(i=0;i<j;i++)
{
printf("%d,",z[i]);
}
printf("\n\nEnter the no u wnt to delet = ");
scanf("%d",&a);
delet(a,z,j);
printf("\n\n***************************************************************");
printf("\n\nTo continue y/n = ");
scanf(" %c",&w);}while((w=='y')||(w=='Y'));
}
/*******************************************************************/

Output

****TO DELET AL THE OCCERENCES****


********************************************************************************
Enter totl no. = 6
Enter no =2
Enter no =6
Enter no =7
Enter no =2
Enter no =4
Enter no =2
U have enter =2,6,7,2,4,2,
Enter the no u wnt to delet = 2
after detetion 2 the list is =6,7,4,
********************************************************************************
To continue y/n =

33

ASSIGNMENT NO. 4
OBJECT:- PROGRAMS BASED ON STACK.
THEORY AND CONCEPTS:A STACK IS ONE OF THE MOST COMMONLY USED DATA STRUCTURE . A STACK, ALSO CALLED A LAST IN FIRST
OUT(LIFO) SYSTEM, IS A LINEAR LIST IN WHICH INSERTIONS AND DELETIONS CAN TAKE PLACE ONLY AT ONE END,
CALLED THE TOP. THE INSERTION AND DELETION OPERATIONS IN STACK TERMINOLOGY ARE KNOWN AS PUSH AND POP
OPERATION.

THE FOLLOWING OPERATIONS ARE PERFORMED ON STACKS:1->INIT(S):- TO INITITALIZE S AS AN EMPTY STACK.


2->PUSH(S,I):- TO PUSH ELEMENT I ONTO STACK S.
3->POP(S):- TO ACCESS AND REMOVE THE TOP ELEMENT OF THE STACK.
4->STACKTOP(S):- TO FIND THE TOP ELEMENT OF THE STACK
5->EMPTY(S):- TO CHECK IF THE STACK IS EMPTY
1-> STACKS

ARE USED TO PASS PARAMETERS BETWEEN FUNCTIONS.

ON A CALL

TO A FUNCTION, THE PARAMETERS AND

LOCAL VARIABLES ARE STORED ON A STACK.

2-> HIGH

LEVEL PROGRAMMING LANGUAGES, SUCH AS

STACK FOR BOOKKEEPING .

REMEMBER

PASCAL, C

ETC, THAT PROVIDES SUPPORT FOR RECURSION USE

IN EACH RECURSIVE CALL, THERE IS NEED TO SAVE THE CURRENT VALUES OF

PARAMETERS , LOCAL VARIABLES AND THE RETURN ADDRESS .


3-> PARENTHESIS CHECKER
4-> MATHEMATICAL NOTATION TRANSLATION.
5-> EVALUATING MATHEMATICAL EXPRESSIONS.
6-> INFIX TO POSTFIX CONVERSION.
7-> QUICK SORT ALGORITHM.

PROBLEMS :(1) WRITE A MENU DRIVEN PROGRAM TO IMPLEMENT THE PUSH, POP AND DISPLAY OPTION OF THE STACK WITH
THE HELP OF STATIC MEMORY ALLOCATION.
(2) WRITE A MENU DRIVEN PROGRAM TO IMPLEMENT THE PUSH, POP AND DISPLAY OPTION OF THE STACK WITH
THE HELP OF DYNAMIC MEMORY ALLOCATION.
(3) WRITE A PROGRAM TO CONVERT A INFIX EXPRESSION TO POSTFIX EXPRESSION.
(4) WRITE A PROGRAM TO CONVERT A INFIX EXPRESSION TO PREFIX EXPRESSION.
(5) WRITE A PROGRAM TO EVALUATE THE GIVEN POSTFIX EXPRESSION.
(6) PROGRAM TO CHECK THE VALIDITY OF THE GIVEN EXPRESSION BASED ON THE PARENTHESIS
(7) PROGRAM TO CHECK THE VALIDITY OF THE GIVEN EXPRESSION BASED ON THE BRACKETS
(8) PROGRAM TO CHECK IF THE GIVEN STRING IS PALINDROME.
(9) PROGRAM FOR SIMULATION OF TWO STACKS ON A SINGLE ARRAY

34

/****************************************************************/
/* Prog for Primitive operations on stack*/
/* By: Akhilesh Kumar Srivastava */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
#define STACKSIZE 100
#define TRUE 1
#define FALSE 0
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void init(struct stack*);
void push(struct stack*,int x);
int pop(struct stack*);
int empty(struct stack*);
int stacktop(struct stack s);
/****************************************************************/
/* Structure Declaraion */
/****************************************************************/
struct stack
{
int item[STACKSIZE];
int top;
};
/****************************************************************/
/****************************************************************/
void main()
{
struct stack s;
int c,x;
char ch;
clrscr();
start:
printf("1. Initialisation of stack\n");
printf("2. Insertion in the stack\n");
printf("3. Removal from the stack\n");
printf("4. Displaying the top Element of the stack\n");
printf("5. exit\n");
printf("===========================\n");
printf("Enter your choice\t");
scanf("%d",&c);
switch(c)
{
case 1: init(&s); break;
case 2: printf("\nEnter the element to be inserted");
scanf("%d",&x);
35

push(&s,x); break;
case 3: x=pop(&s);
printf("\nRemoved item is:=> \t%d",x); break;
case 4: x=stacktop(s);
printf("\nStacktop item is:=> \t%d",x); break;
case 5: exit(1);
default: printf("\nWrong choice"); break;
}
printf("\nDo you wish to continue? (y/n) ");
fflush(stdin);
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
goto start;
}
/****************************************************************/
/******************* Function Definitions ***********************/
/****************************************************************/
/********************* Initialization of stack ******************/
/****************************************************************/
void init(struct stack *s)
{
s->top=-1;
}
/****************************************************************/
/******************* checking if stack is empty *****************/
/****************************************************************/
int empty(struct stack *s)
{
if(s->top==-1)
return TRUE;
else
return FALSE;
}
/****************************************************************/
/***************** Insertion of an item in stack ****************/
/****************************************************************/
void push(struct stack *s,int x)
{
if(s->top==STACKSIZE-1)
{
printf("stack overflow");
exit(1);
}
s->top++;
36

s->item[s->top]=x;
}
/****************************************************************/
/*************** Removal of an item from stack ******************/
/****************************************************************/
int pop(struct stack *s)
{
int y;
if(empty(s))
{
printf("Stack Underflows");
exit(1);
}
y=s->item[s->top];
s->top--;
return(y);
}
/****************************************************************/
/************** Displaying top element of the stack *************/
/****************************************************************/
int stacktop(struct stack s)
{
int y;
y=s.item[s.top];
return(y);
}
/****************************************************************/

37

Output
1. Initialisation of stack
2. Insertion in the stack
3. Removal from the stack
4. Displaying the top Element of the stack
5. exit
===========================
Enter your choice
1
Do you wish to continue? (y/n) y
1. Initialisation of stack
2. Insertion in the stack
3. Removal from the stack
4. Displaying the top Element of the stack
5. exit
===========================
Enter your choice
2
Enter the element to be inserted100
Do you wish to continue? (y/n) y
1. Initialisation of stack
2. Insertion in the stack
3. Removal from the stack
4. Displaying the top Element of the stack
5. exit
===========================
Enter your choice
2
Enter the element to be inserted200
Do you wish to continue? (y/n) y
1. Initialisation of stack
2. Insertion in the stack
3. Removal from the stack
4. Displaying the top Element of the stack
5. exit
===========================
Enter your choice
3
Removed item is:=> 200
Do you wish to continue? (y/n) y
1. Initialisation of stack
2. Insertion in the stack
3. Removal from the stack
4. Displaying the top Element of the stack
5. exit
===========================
Enter your choice
4
Stacktop item is:=> 100
Do you wish to continue? (y/n)

38

/****************************************************************/
/* Prog for Conversion of Infix expression to Postfix using Stacks */
/* By: Akhilesh Kumar Srivastava */
/* Des: The evaluation is based on simulation of operator stack */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#define STACKSIZE 100
#define TRUE 1
#define FALSE 0
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void init(struct stack*);
void push(struct stack*,char x);
char pop(struct stack*);
int empty(struct stack*);
int prcd(char,char);
char stacktop(struct stack s);
/****************************************************************/
/* Structure Declaraion */
/****************************************************************/
struct stack
{
char item[STACKSIZE];
int top;
};
/****************************************************************/
void main()
{
char infix[20],postfix[20],symb,topsymb;
int i=0,j=0;
struct stack s;
init(&s);
printf("Enter the infix expression:=>\t");
scanf("%s",infix);
while(infix[i]!='\0')
{
symb=infix[i];
if(symb>='a'&&symb<='z')
{ postfix[j]=symb; j++; }
else
{
while(!empty(&s)&&prcd(stacktop(s),symb))
{
topsymb=pop(&s);
postfix[j]=topsymb; j++;
}
push(&s,symb);
}
i++;
39

}
while(!empty(&s))
{
topsymb=pop(&s);
postfix[j]=topsymb; j++;
}
postfix[j]='\0';
printf("\nthe postfix expression is:=> %s",postfix);
getch();
}
/****************************************************************/
/******************* Function Definitions ***********************/
/****************************************************************/
/************* Primitive operations on stack ********************/
/****************************************************************/
void init(struct stack *s)
{
s->top=-1;
}
/****************************************************************/
int empty(struct stack *s)
{
if(s->top==-1)
return TRUE;
else
return FALSE;
}
/****************************************************************/
void push(struct stack *s,char x)
{
if(s->top==STACKSIZE-1)
{
printf("stack overflow");
exit(1);
}
s->top++;
s->item[s->top]=x;
}
/****************************************************************/
char pop(struct stack *s)
{
char y;
if(empty(s))
{
printf("Stack Underflows");
exit(1);
}
y=s->item[s->top];
s->top--;
return(y);
40

}
/****************************************************************/
char stacktop(struct stack s)
{
char y;
y=s.item[s.top];
return(y);
}
/****************************************************************/
/******************** Precedence Function ***********************/
/* The function checks the precedence of operator over b. If a has
higher precedence than b, it returns true and false otherwise */
/****************************************************************/
int prcd(char a,char b)
{
if(a=='$')
{
if(b=='$') return FALSE;
else
return TRUE;
}
if(a=='*'||a=='/')
{
if(b=='$') return FALSE;
else
return TRUE;
}
if(a=='+'||a=='-')
{
if(b=='+'||b=='-')
else
}

return TRUE;
return FALSE;

}
/****************************************************************/

Output
Enter the infix expression:=> a+b*c-d/e$f$g
the postfix expression is:=> abc*+defg$$/-

41

/****************************************************************/
/* Prog for Conversion of Infix expression to Prefix using Stack*/
/* By: Akhilesh Kumar Srivastava
*/
/* Des: The evaluation is based on simulation of operator stack */
/****************************************************************/
/****************** Pre-processoer directives *******************/
/****************************************************************/
#include<string.h>
#define STACKSIZE 100
#define TRUE 1
#define FALSE 0
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void init(struct stack*);
void push(struct stack*,char x);
char pop(struct stack*);
int empty(struct stack*);
int prcd(char,char);
char stacktop(struct stack s);
/****************************************************************/
/* Structure Declaraion */
/****************************************************************/
struct stack
{
char item[STACKSIZE];
int top;
};
/****************************************************************/
void main()
{
char infix[20],prefix[20],symb,topsymb;
int i=0,j=0;
struct stack s;
init(&s);
printf("Enter the infix expression:=>\t");
scanf("%s",infix);
strrev(infix);
while(infix[i]!='\0')
{
symb=infix[i];
if(symb>='a'&&symb<='z')
{ prefix[j]=symb; j++; }
else
{
while(!empty(&s)&&!prcd(symb,stacktop(s)))
{
topsymb=pop(&s);
prefix[j]=topsymb; j++;
}
42

push(&s,symb);
}
i++;
}
while(!empty(&s))
{
topsymb=pop(&s);
prefix[j]=topsymb; j++;
}
prefix[j]='\0';
strrev(prefix);
printf("\nthe prefix expression is:=> %s",prefix);
getch();
}
/****************************************************************/
/******************* Function Definitions ***********************/
/****************************************************************/
/************* Primitive operations on stack ********************/
/****************************************************************/
void init(struct stack *s)
{
s->top=-1;
}
/****************************************************************/
int empty(struct stack *s)
{
if(s->top==-1)
return TRUE;
else
return FALSE;
}
/****************************************************************/
void push(struct stack *s,char x)
{
if(s->top==STACKSIZE-1)
{
printf("stack overflow");
exit(1);
}
s->top++;
s->item[s->top]=x;
}
/****************************************************************/
char pop(struct stack *s)
{
char y;
if(empty(s))
{
printf("Stack Underflows");
exit(1);
43

}
y=s->item[s->top];
s->top--;
return(y);
}
/****************************************************************/
char stacktop(struct stack s)
{
char y;
y=s.item[s.top];
return(y);
}
/****************************************************************/
/******************** Precedence Function ***********************/
/* The function checks the precedence of operator over b. If a has
higher precedence than b, it returns true and false otherwise */
/****************************************************************/
int prcd(char a,char b)
{
if(a=='$')
{
if(b=='$') return FALSE;
else
return TRUE;
}
if(a=='*'||a=='/')
{
if(b=='$') return FALSE;
else
return TRUE;
}
if(a=='+'||a=='-')
{
if(b=='+'||b=='-')
else
}

return TRUE;
return FALSE;

}
/****************************************************************/

Output
Enter the infix expression:=> a+b*c/d
the prefix expression is:=> +a/*bcd

44

/****************************************************************/
/* Program for Evaluation of Postfix expression using Stacks */
/* By: Akhilesh Kumar Srivastava */
/* Des: The evaluation is based on simulation of operand stack */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#define STACKSIZE 100
#define TRUE 1
#define FALSE 0
/****************************************************************/
/* Function Prototyping */
void init(struct stack*);
void push(struct stack*,int x);
int pop(struct stack*);
int empty(struct stack*);
int val(char op,int x,int y);
/****************************************************************/
/* Structure Declaraion */
/****************************************************************/
struct stack
{
int item[STACKSIZE];
int top;
};
/****************************************************************/
void main()
{
char post[20],symb;
int i=0,opnd1,opnd2,value;
struct stack s;
init(&s);
printf("Enter the Postfix expression:=>\t");
scanf("%s",post);
while(post[i]!='\0')
{
symb=post[i];
if(symb>='0'&&symb<='9')
push(&s,symb-'0');
else
{
opnd2=pop(&s);
opnd1=pop(&s);
value=val(symb,opnd1,opnd2);
push(&s,value);
}
i++;
}
printf("\nValue of the expression is:=> %d",pop(&s));
getch();
}
45

/****************************************************************/
/******************* Function Definitions ***********************/
/****************************************************************/
/************* Primitive operations on stack ********************/
/****************************************************************/
void init(struct stack *s)
{
s->top=-1;
}
/****************************************************************/
int empty(struct stack *s)
{
if(s->top==-1)
return TRUE;
else
return FALSE;
}
/****************************************************************/
void push(struct stack *s,int x)
{
if(s->top==STACKSIZE-1)
{
printf("stack overflow");
exit(1);
}
s->top++;
s->item[s->top]=x;
}
/****************************************************************/
int pop(struct stack *s)
{
int y;
if(empty(s))
{
printf("Stack Underflows");
exit(1);
}
y=s->item[s->top];
s->top--;
return(y);
}
/****************************************************************/
int val(char op,int opnd1,int opnd2)
{
int v;
switch(op)
{
case '+': v=opnd1+opnd2; break;
case '*': v=opnd1*opnd2; break;
46

case '/': v=opnd1/opnd2;


break;
case '-': v=opnd1-opnd2;
break;
case '$': v=pow(opnd1,opnd2);break;
}
return v;
}
/****************************************************************/

Output
Enter the Postfix expression:=> 68*422$/-52*+
Value of the expression is:=> 58

47

/****************************************************************/
/* Program for Evaluation of Prefix expression using Stacks
*/
/* By: Akhilesh Kumar Srivastava
*/
/****************************************************************/
/****************** Pre-processoer directives *******************/
#define STACKSIZE 100
#define TRUE 1
#define FALSE 0
/****************************************************************/
/* Function Prototyping */
void init(struct stack*);
void push(struct stack*,char x);
char pop(struct stack*);
int empty(struct stack*);
int val(char op,int x,int y);
/****************************************************************/
/* Structure Declaraion */
/****************************************************************/
struct stack
{
char item[STACKSIZE];
int top;
};
/****************************************************************/
void main()
{
char pre[20],symb,op;
int i=0,opnd1,opnd2,value;
struct stack ops,opnds;
clrscr();
init(&ops);
init(&opnds);
printf("Enter the Prefix expression:=>\t");
scanf("%s",pre);
while(pre[i]!='\0')
{
symb=pre[i];
if(symb>='0'&&symb<='9')
push(&opnds,symb);
else
{
if(symb=='+'||symb=='-'||symb=='*'||symb=='/'||symb=='$')
push(&ops,symb);
else
{
if(symb==')')
{
opnd2=pop(&opnds)-'0';
opnd1=pop(&opnds)-'0';
op=pop(&ops);
value=val(op,opnd1,opnd2);
push(&opnds,value+'0');
}
}
}
i++;
}
printf("\nValue of the expression is:=> %d",pop(&opnds)-'0');
getch();

48

}
/****************************************************************/
/******************* Function Definitions ***********************/
/****************************************************************/
/************* Primitive operations on stack ********************/
/****************************************************************/
void init(struct stack *s)
{
s->top=-1;
}
/****************************************************************/
int empty(struct stack *s)
{
if(s->top==-1)
return TRUE;
else
return FALSE;
}
/****************************************************************/
void push(struct stack *s,char x)
{
if(s->top==STACKSIZE-1)
{
printf("stack overflow");
exit(1);
}
s->top++;
s->item[s->top]=x;
}
/****************************************************************/
char pop(struct stack *s)
{
int y;
if(empty(s))
{
printf("Stack Underflows");
exit(1);
}
y=s->item[s->top];
s->top--;
return(y);
}
/****************************************************************/
int val(char op,int opnd1,int opnd2)
{
int v;
switch(op)
{
case '+': v=opnd1+opnd2;
break;
case '*': v=opnd1*opnd2;
break;
case '/': v=opnd1/opnd2;
break;
case '-': v=opnd1-opnd2;
break;
case '$': v=pow(opnd1,opnd2);break;
}
return v;
}

49

Output:->
--------Enter the Prefix expression:=>

(+12)

Value of the expression is:=> 3


----------------------------------------Enter the Prefix expression:=>
(+(*42)3)
Value of the expression is:=> 11
-----------------------------------------

50

/****************************************************************/
/* Prog for Validity of expression based on parenthesis */
/* By: Akhilesh Kumar Srivastava */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#define STACKSIZE 100
#define TRUE 1
#define FALSE 0
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct stack
{
char item[STACKSIZE];
int top;
};
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void init(struct stack *);
void push(struct stack *,char x);
char pop(struct stack *);
int empty(struct stack *);
/****************************************************************/
void main()
{
struct stack s;
int i;
char x;
char exp[20];
clrscr();
init(&s);
printf("Enter the infix expression with paranthesis");
scanf("%s",exp);
for(i=0;exp[i]!='\0';i++)
{
if(exp[i]=='(')
push(&s,exp[i]);
if(exp[i]==')')
x=pop(&s);
}
if(empty(&s))
printf("\n\tThe Expression is correct");
else
printf("\n\tThe Expression is not correct");
getch();
}
/****************************************************************/
/* Function Definitions */
51

/****************************************************************/
/************** Initializing the stack **************************/
/****************************************************************/
void init(struct stack *ps)
{
ps->top=-1;
}
/****************************************************************/
/*************** Inserting an item in the stack *****************/
/****************************************************************/
void push(struct stack *ps,char x)
{
if(ps->top==STACKSIZE-1)
{
printf("stack Overflows");
exit(1);
}
ps->top++;
ps->item[ps->top]=x;
}
/****************************************************************/
/*************** Removing an item from the stack ****************/
/****************************************************************/
char pop(struct stack *ps)
{
char x;
if(empty(ps))
{
printf("Stack Underflows");
exit(1);
}
x=ps->item[ps->top];
ps->top--;
return x;
}
/****************************************************************/
/**************** checking if the stack is empty ****************/
/****************************************************************/
int empty(struct stack *ps)
{
if(ps->top==-1)
return TRUE;
else
return FALSE;
}
/****************************************************************/

52

Output
Enter the infix expression with paranthesisa+(b-c*(d/e))
The Expression is correct
Enter the infix expression with paranthesisa+(b-c*(d-e)
The Expression is not correct

53

/****************************************************************/
/* Prog for Prog for Validity of expression based on [, { & ( brackets*/
/* By: Akhilesh Kumar Srivastava */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#define STACKSIZE 100
#define TRUE 1
#define FALSE 0
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct stack
{
char item[STACKSIZE];
int top;
};
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void init(struct stack *);
void push(struct stack *,char x);
char pop(struct stack *);
char stacktop(struct stack *);
int empty(struct stack *);
/****************************************************************/
void main()
{
struct stack s;
int i;
char x;
char exp[20];
clrscr();
init(&s);
printf("Enter the infix expression with paranthesis");
scanf("%s",exp);
for(i=0;exp[i]!='\0';i++)
{
if(exp[i]=='('||exp[i]=='{'||exp[i]=='[')
push(&s,exp[i]);
else
{
if(exp[i]==']')
{
if(stacktop(&s)=='[')
x=pop(&s);
}
if(exp[i]=='}')
{
if(stacktop(&s)=='{')
x=pop(&s);
54

}
if(exp[i]==')')
{
if(stacktop(&s)=='(')
x=pop(&s);
}
}
}
if(empty(&s))
printf("\n\tThe Expression is correct");
else
printf("\n\tThe Expression is not correct");
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Initializing the stack **************************/
/****************************************************************/
void init(struct stack *ps)
{
ps->top=-1;
}
/****************************************************************/
/*************** Inserting an item in the stack *****************/
/****************************************************************/
void push(struct stack *ps,char x)
{
if(ps->top==STACKSIZE-1)
{
printf("stack Overflows");
exit(1);
}
ps->top++;
ps->item[ps->top]=x;
}
/****************************************************************/
/*************** Removing an item from the stack ****************/
/****************************************************************/
char pop(struct stack *ps)
{
char x;
if(empty(ps))
{
printf("Stack Underflows");
exit(1);
}
x=ps->item[ps->top];
55

ps->top--;
return x;
}
/****************************************************************/
/*********** Returning the top element of the stack *************/
/****************************************************************/
char stacktop(struct stack *ps)
{
char x;
x=ps->item[ps->top];
return x;
}
/****************************************************************/
/**************** checking if the stack is empty ****************/
/****************************************************************/
int empty(struct stack *ps)
{
if(ps->top==-1)
return TRUE;
else
return FALSE;
}
/****************************************************************/

Output
Enter the infix expression with paranthesisa+[b-{c+(d/e)}]
The Expression is correct
Enter the infix expression with paranthesisa+[b-c*{d/e]}
The Expression is not correct

56

/****************************************************************/
/*Prog for Finding if the given string is palindrome using stacks*/
/* By: Akhilesh Kumar Srivastava */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#define STACKSIZE 100
#define TRUE 1
#define FALSE 0
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void init(struct stack*);
void push(struct stack*,char x);
char pop(struct stack*);
int empty(struct stack*);
char stacktop(struct stack s);
/****************************************************************/
/* Structure Declaraion */
/****************************************************************/
struct stack
{
char item[STACKSIZE];
int top;
};
/****************************************************************/
/****************************************************************/
void main()
{
struct stack s;
int i=0,x;
char str[20],flag='f';
clrscr();
init(&s);
printf("Enter the string");
scanf("%s",str);
while(str[i]!='\0')
{
push(&s,str[i]);
i++;
}
i=0;
while(!empty(&s))
{
if(str[i]!=stacktop(s))
{ flag='f';
break;
}
else
{
x=pop(&s);
57

flag='t';
}
i++;
}
if(flag=='f')
printf("\nEntered string is not a palindrome");
else
printf("\nEntered string is a palindrome");
getch();
}
/****************************************************************/
/******************* Function Definitions ***********************/
/****************************************************************/
/********************* Initialisation of stack ******************/
/****************************************************************/
void init(struct stack *s)
{
s->top=-1;
}
/****************************************************************/
/******************* checking if stack is empty *****************/
/****************************************************************/
int empty(struct stack *s)
{
if(s->top==-1)
return TRUE;
else
return FALSE;
}
/****************************************************************/
/***************** Insertion of an item in stack ****************/
/****************************************************************/
void push(struct stack *s,char x)
{
if(s->top==STACKSIZE-1)
{
printf("stack overflow");
exit(1);
}
s->top++;
s->item[s->top]=x;
}
/****************************************************************/
/*************** Removal of an item from stack ******************/
/****************************************************************/
char pop(struct stack *s)
{
char y;
if(empty(s))
58

{
printf("Stack Underflows");
exit(1);
}
y=s->item[s->top];
s->top--;
return(y);
}
/****************************************************************/
/************** Displaying top element of the stack *************/
/****************************************************************/
char stacktop(struct stack s)
{
char y;
y=s.item[s.top];
return(y);
}
/****************************************************************/

Output
Enter the string
Akhilesh
Entered string is not a palindrome
Enter the string
dalda
Entered string is a palindrome

59

/********************************************************************/
/*To Simulate TWO stacks on a single array*/
/* By: Vaibhav Verma */
/* CSE Second Year 'D' Section */
/********************************************************************/
/******************** Pre-processoer directives *********************/
#include<stdio.h>
#include<conio.h>
#include<dos.h>
#include<process.h>
#include<stdlib.h>
#define size 6 //defining the max size of an array
/********************************************************************/
/****declaration of stack using structures****
here we tack two top pointers for respective stacks*/
/********************************************************************/
struct stack
{
int a[size],top1,top2;
}s;
/********************************************************************/
/*defining empty operation (to check empty condition) for stacks*/
/********************************************************************/
int empty(struct stack *s,int n)
{
if(n==1)
return( s->top1== -1);
return( s->top2== size);
}
/********************************************************************/
/*defining init operation (TO INITIALISE THE STACK) for stacks*/
/********************************************************************/
void init(struct stack *s,int n)
{
if(n==1)
s->top1=-1;
else
s->top2=size;
}
/********************************************************************/
/*defining push operation (TO PUSH ANY ELEMENT IN A STACK) for stacks*/
/********************************************************************/
void push(struct stack *s, int x,int n)
{
if(n==1)
{
if(s->top1+1==s->top2)
{
printf("First stack overflow");
60

exit(1);
}
s->a[++(s->top1)]=x;
}
else if(n==2)
{
if(s->top2-1==s->top1)
{
printf("Second stack overflow");
exit(1);
}
s->a[--(s->top2)]=x;
}
}
/********************************************************************/
/*defining pop operation (TO EMOVE THE TOPMOST ELEMENT OF STACK) for
stacks*/
/********************************************************************/
int pop(struct stack *s,int n)
{
if(empty(s,n))
{
printf("%dth stack underflow",n);
exit(1);
}
if(n==1)
return( s->a[(s->top1)--]);
return( s->a[(s->top2)++]);
}
/********************************************************************/
/*defining stacktop operation(TO RETURN THE TOPMOST ELEMENT) for stacks*/
/********************************************************************/
void stacktop(struct stack *s,int n)
{
if(!empty(s,n))
{
if(n==1)
printf(" Top item of first stack is =%d",(s->a[s->top1]));
else
printf(" Top item of first stack is =%d",(s->a[s->top2]));
}
}
/********************************************************************/
/*defining printstack operation(TO PRINT PRESENT STACK CONDITION) for
stacks*/
/********************************************************************/
void printstack(struct stack *s,int n)
{
int i;
if(!empty(s,n))
61

{
if(n==1)
{
printf("The curnt element in FIRST the stack is = ");
for(i=0;i<=s->top1;i++)
printf("%d,",s->a[i]);
}
else if(n==2)
{
printf("The curnt element in SECOND the stack is = ");
for(i=size-1;i>=s->top2;i--)
printf("%d,",s->a[i]);
}
}
}
/********************************************************************/
void main()
{
int i,j,k,l;
clrscr();
init(&s,1);
init(&s,2); //init both stacks
printf("\n\nEnter the required option "
"\nFor init press
= 11/12"
"\nFor push press
= 21/22"
"\nFor pop press
= 31/32"
"\nFor stack top
= 41/42"
"\nFor exit press
= 5");
printf("\n\nNOTE:-To enter the stack add the stack no. AFTER the option no.");
print:printf("\n\nEnter the option = ");
scanf("%d",&i);
switch(i/10)
{
case 1:
init(&s,i%10);
printf("The %dth stack is initialised ",i%10);
goto print;
case 2:
printf("Enter the no u want to push = ");
scanf("%d",&j);
push(&s,j,i%10);
printstack(&s,i%10);
goto print;
case 3:
printf("\nThe element removed from stack %d is = %d\n",i%10,pop(&s,i%10));
if(empty(&s,i%10))
62

printf("Stack is now empty ");


printstack(&s,i%10);
case 4:
stacktop(&s,i%10);
goto print;
case 5:
exit(1);
}
getch();
}

63

/***************************************************************************/

Output
/***************************************************************************/
Enter the required option
For init press
= 11/12
For push press
= 21/22
For pop press
= 31/32
For stack top
= 41/42
For exit press
=5
NOTE:-To enter the stack add the stack no. AFTER the option no.
Enter the option = 11
The 1th stack is initialised
Enter the option = 12
The 2th stack is initialised
Enter the option = 21
Enter the no u want to push = 1
The curnt element in FIRST the stack is = 1,
Enter the option = 22
Enter the no u want to push = 2
The curnt element in SECOND the stack is = 2,
Enter the option = 21
Enter the no u want to push = 5
The curnt element in FIRST the stack is = 1,5,
Enter the option = 22
Enter the no u want to push = 8
The curnt element in SECOND the stack is = 2,8,
Enter the option = 21
Enter the no u want to push = 6
The curnt element in FIRST the stack is = 1,5,6,
Enter the option = 22
Enter the no u want to push = 7
The curnt element in SECOND the stack is = 2,8,7,
Enter the option = 22
Enter the no u want to push = 4
Second stack overflow
***************************************************************************
Enter the required option
For init press
= 11/12
64

For push press


For pop press
For stack top
For exit press

= 21/22
= 31/32
= 41/42
=5

NOTE:-To enter the stack add the stack no. AFTER the option no.
Enter the option = 11
The 1th stack is initialised
Enter the option = 12
The 2th stack is initialised
Enter the option = 21
Enter the no u want to push = 5
The curnt element in FIRST the stack is = 5,
Enter the option = 21
Enter the no u want to push = 6
The curnt element in FIRST the stack is = 5,6,
Enter the option = 31
The element removed from stack 1 is = 6
The curnt element in FIRST the stack is = 5, Top item of first stack is =5
Enter the option = 31
The element removed from stack 1 is = 5
Stack is now empty
Enter the option = 31
1th stack underflow
****************************************************************************
Enter the required option
For init press
= 11/12
For push press
= 21/22
For pop press
= 31/32
For stack top
= 41/42
For exit press
=5
NOTE:-To enter the stack add the stack no. AFTER the option no.
Enter the option = 21
Enter the no u want to push = 5
The curnt element in FIRST the stack is = 5,
Enter the option = 22
65

Enter the no u want to push = 6


The curnt element in SECOND the stack is = 6,
Enter the option = 22
Enter the no u want to push = 5
The curnt element in SECOND the stack is = 6,5,
Enter the option = 21
Enter the no u want to push = 7
The curnt element in FIRST the stack is = 5,7,
Enter the option = 41
Top item of first stack is =7
Enter the option = 42
Top item of first stack is =5
Enter the option = 5
/***************************************************************************/

66

ASSIGNMENT NO. 5
OBJECT:- PROGRAMS BASED ON QUEUES.
THEORY AND CONCEPTS:IN THE

CONTEXT OF DATA STRUCTURES , A QUEUE IS A LINEAR LIST IN WHICH INSERTIONS CAN TAKE PLACE AT ONE END

OF THE LIST, CALLED THE REAR OF THE LIST, AND DELETIONS CAN TAKE PLACE ONLY AT OTHER END CALLED THE FRONT
OF THE LIST.

THE BEHAVIOR OF A QUEUE IS LIKE A FIRST IN FIRST OUT SYSTEM.

THE FOLLOWING OPERATIONS ARE PERFORMED ON QUEUE:1->INIT(Q):- TO INITIALIZE Q AS AN EMPTY QUEUE


2->INSERT(Q,I):-TO INSERT(ADD) ELEMENT I IN A QUEUE Q.
3->REMOVE(Q):- TO ACCESS AND REMOVE AN ELEMENT OF THE QUEUE.
4->EMPTY(Q):- TO CHECK IF THE QUEUE IS EMPTY.

THE FOLLOWING ARE THE APPLICATIONS OF QUEUES:1->THERE

ARE SEVERAL ALGORITHMS THAT USE QUEUES TO SOLVE PROBLEMS EFFICIENTLY.

FOR EXAMPLE

WE HAVE

USED QUEUE FOR PERFORMING LEVEL ORDER TRAVERSAL OF A BINARY TREE AND FOR PERFORMING BREADTH FIRST
SEARCH ON A GRAPH.

2->WHEN

THE JOBS ARE SUBMITTED TO A NETWORKED PRINTER, THEY ARE ARRANGED IN ORDER OF ARRIVAL .

THUS

ESSENTIALLY JOBS SENT TO A PRINTER ARE PLACED ON A QUEUE.

3->THERE IS A KIND OF COMPUTER NETWORK WHERE DISK IS ATTACHED TO ONE COMPUTER KNOWN AS FILE SERVER.
USERS ON OTHER COMPUTERS ARE GIVEN ACCESS TO FILES ON A FIRST COME FIRST SERVED BASIS. SO THE DATA
STRUCTURE IS QUEUE.
4->VIRTUALLY EVERY REAL LIFE LINE(SUPPOSED TO BE) A QUEUE. FOR EXAMPLE LINES AT TICKET COUNTERS AT
CINEMA HALLS, RAILWAY STATIONS, BUS STANDS ETC. ARE QUEUES, BECAUSE THE SERVICE IS PROVIDED ON FIRST
COME FIRST SERVED BASIS.
PROBLEMS :(1) WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS OPERATIONS ON A LINEAR QUEUE WITH THE HELP
OF STATIC MEMORY ALLOCATION.
(2) WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS OPERATIONS ON A LINEAR QUEUE WITH THE HELP
OF DYNAMIC MEMORY ALLOCATION.
(3) WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS OPERATIONS ON A CIRCULAR QUEUE WITH THE
HELP OF STATIC MEMORY ALLOCATION.
(4) WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS OPERATIONS ON A DEQUEUE QUEUE WITH THE
HELP OF STATIC MEMORY ALLOCATION.
(5) WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS OPERATIONS ON A PRIORITY QUEUE WITH THE
HELP OF STATIC MEMORY ALLOCATION.

67

/****************************************************************/
/* Prog for Primtive operations on linear queue */
/* By: Akhilesh Kumar Srivastava */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
#define MAXQUEUE 100
#define TRUE 1
#define FALSE 0
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct queue
{
int item[MAXQUEUE];
int front;
int rear;
};
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void init(struct queue *pq);
void insert(struct queue *pq,int x);
int remov(struct queue *pq);
int empty(struct queue *pq);
/****************************************************************/
void main()
{
struct queue q;
int x,c;
char ch;
clrscr();
init(&q);
start:
printf("1. Initialise the queue\n");
printf("2. Insert in the queue\n");
printf("3. Remove from the queue\n");
printf("4. exit\n");
printf("===========================\n");
printf("Enter your choice\t");
scanf("%d",&c);
switch(c)
{
case 1:
init(&q); break;
case 2: printf("\nEnter the element to be inserted");
scanf("%d",&x);
insert(&q,x); break;
68

case 3: x=remov(&q);
printf("\nRemoved item is:=> \t%d",x); break;
case 4:
exit(1);
default: printf("\nWrong choice"); break;
}
printf("\nDo you wish to continue? (y/n) ");
fflush(stdin);
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
goto start;
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/******************** Iniailizing the queue *********************/
/****************************************************************/
void init(struct queue *pq)
{
pq->rear=-1;
pq->front=0;
}
/****************************************************************/
/******************** Insertion in the queue ********************/
/****************************************************************/
void insert(struct queue *pq,int x)
{
if(pq->rear==MAXQUEUE-1)
{
printf("Queue Overflows");
exit(1);
}
pq->rear++;
pq->item[pq->rear]=x;
}
/****************************************************************/
/******************** Removal from the queue ********************/
/****************************************************************/
int remov(struct queue *pq)
{
int x;
if(empty(pq))
{
printf("Queue Underflows");
exit(1);
}
x=pq->item[pq->front];
pq->front--;
return x;
}
69

/****************************************************************/
/***********Checking if the queue is empty **********************/
/****************************************************************/
int empty(struct queue *pq)
{
if(pq->rear-pq->front+1==0)
return TRUE;
else
return FALSE;
}
/****************************************************************/

Output
1. Initialise the queue
2. Insert in the queue
3. Remove from the queue
4. exit
===========================
Enter your choice
1
Do you wish to continue? (y/n) y
1. Initialise the queue
2. Insert in the queue
3. Remove from the queue
4. exit
===========================
Enter your choice
2
Enter the element to be inserted100
Do you wish to continue? (y/n) y
1. Initialise the queue
2. Insert in the queue
3. Remove from the queue
4. exit
===========================
Enter your choice
3
Removed item is:=> 100
Do you wish to continue? (y/n) y
1. Initialise the queue
2. Insert in the queue
3. Remove from the queue
4. exit
===========================
Enter your choice
2
Enter the element to be inserted500

70

/****************************************************************/
/* Prog for Primtive operations on Circular queue */
/* By: Akhilesh Kumar Srivastava */
/* Des: Overcomes the limitaitons of linear Queue */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
#define MAXQUEUE 100
#define TRUE 1
#define FALSE 0
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct queue
{
int item[MAXQUEUE];
int front;
int rear;
};
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void init(struct queue *pq);
void insert(struct queue *pq,int x);
int remov(struct queue *pq);
int empty(struct queue *pq);
/****************************************************************/
void main()
{
struct queue q;
int x,c;
char ch;
clrscr();
init(&q);
start:
printf("1. Initialise the queue\n");
printf("2. Insert in the queue\n");
printf("3. Remove from the queue\n");
printf("4. exit\n");
printf("===========================\n");
printf("Enter your choice\t");
scanf("%d",&c);
switch(c)
{
case 1:
case 2:

init(&q); break;
printf("\nEnter the element to be inserted");
scanf("%d",&x);
71

case 3:
case 4:
default:
}

insert(&q,x); break;
x=remov(&q);
printf("\nRemoved item is:=> \t%d",x); break;
exit(1);
printf("\nWrong choice"); break;

printf("\nDo you wish to continue? (y/n) ");


fflush(stdin);
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
goto start;
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
void init(struct queue *pq)
{
pq->rear=MAXQUEUE-1;
pq->front=MAXQUEUE-1;
}
/****************************************************************/
void insert(struct queue *pq,int x)
{
if(pq->rear==MAXQUEUE-1)
pq->rear==0;
else
pq->rear++;
if(pq->front==pq->rear)
{
printf("Queue Overflows");
exit(1);
}
pq->item[pq->rear]=x;
}
/****************************************************************/
int remov(struct queue *pq)
{
int x;
if(empty(pq))
{
printf("Queue Underflows");
exit(1);
}
if(pq->front==MAXQUEUE-1)
pq->front=0;
else
pq->front++;
72

x=pq->item[pq->front];
return x;
}
/****************************************************************/
int empty(struct queue *pq)
{
if(pq->rear==pq->front)
return TRUE;
else
return FALSE;
}
/****************************************************************/

Output
1. Initialise the queue
2. Insert in the queue
3. Remove from the queue
4. exit
===========================
Enter your choice
1
Do you wish to continue? (y/n) y
1. Initialise the queue
2. Insert in the queue
3. Remove from the queue
4. exit
===========================
Enter your choice
2
Enter the element to be inserted100
Do you wish to continue? (y/n) y
1. Initialise the queue
2. Insert in the queue
3. Remove from the queue
4. exit
===========================
Enter your choice
3
Removed item is:=> 100
Do you wish to continue? (y/n) y
1. Initialise the queue
2. Insert in the queue
3. Remove from the queue
4. exit
===========================
Enter your choice
2
Enter the element to be inserted500

73

/********************************************************************/
/*To Implement Ascending Priority Queue */
/* By: Rakesh Menon */
/* CSE Second Year 'D' Section */
/********************************************************************/
/******************** Pre-processoer directives *********************/
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
/********************************************************************/
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct priorityqueue
{
int info;
struct priorityqueue *next;
};
/********************************************************************/
typedef struct priorityqueue pq;
/************ Global declaration of Pointers ***********************/
pq *front,*rear;
/********************************************************************/
/* Function Definitions */
/********************************************************************/
void *getnode()
{
pq *ptr;
ptr=(pq*)malloc(sizeof(pq));
return ptr;
}
/********************************************************************/
void init(pq **front,pq **rear)
{
*front=(pq*)NULL;
*rear=(pq*)NULL;
}
/********************************************************************/
void insert(int item)
{
pq *ptr;
ptr=getnode();
ptr->info=item;
if(front==(pq*)NULL && rear==(pq*)NULL)
{
ptr->next=(pq*)NULL;
front=rear=ptr;
}
else
{
74

ptr->next=(pq*)NULL;
rear->next=ptr;
rear=ptr;
}
}
/********************************************************************/
int delbeg(pq **front)
{
int p;
p=(*front)->info;
if((*front)==rear)
(*front)=rear=(pq*)NULL;
else (*front)=(*front)->next;
return p;
}
/********************************************************************/
int delafter(pq **p)
{
pq *q;
int x;
q=(*p)->next;
x=q->info;
(*p)->next=q->next;
free(q);
return x;
}
/********************************************************************/
int delprio()
{
pq *ptr;
int c=0,l=1;
int min=front->info,pos=0,x;
ptr=front;
while(ptr!=(pq*)NULL)
{
if(ptr->info<min)
{
min=ptr->info;
pos=c;
}
c++;
ptr=ptr->next;
}
ptr=front;
while(l<pos)
{
ptr=ptr->next;
l++;
}
if(pos==0)
75

{
x=delbeg(&front);
}
else x=delafter(&ptr);
if(front==(pq*)NULL)
rear=(pq*)NULL;
return x;
}
/********************************************************************/
void printq()
{
pq *p;
if(front==(pq*)NULL && rear==(pq*)NULL)
printf("\nQueue is empty");
p=front;
while(p!=(pq*)NULL)
{
printf("%d ",p->info);
p=p->next;
}
}
/********************************************************************/
void main()
{
int ch=1,item,x;
init(&front,&rear);
do
{
clrscr();
printf("Priority Queue\n");
printf("--------------\n");
printf("1.Insert element.\n\n");
printf("2.Delete element ASCENDING.\n\n");
printf("3.EXIT.\n\n\n");
printf("Enter choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter element for insertion:");
scanf("%d",&item);
insert(item);
printq();
getch();
break;
case 2:if(front==(pq*)NULL && rear==(pq*)NULL)
printf("\nNo elements left to delete\n");
else
{
x=delprio();
printf("%d\n",x);
76

}
printq();
getch();
break;
case 3:exit(0);
default:break;
}
}while(ch!=3);
}
/********************************************************************/

77

ASSIGNMENT NO. 6
OBJECT :- PROGRAMS BASED ON LINKED LIST.
THEORY AND CONCEPTS:A LINKED LIST IS A LINEAR COLLECTION OF DATA ELEMENTS, CALLED NODES. THE LINEAR ORDER IS GIVEN BY POINTERS.
EACH NODE IS DIVIDED INTO TWO OR MORE PARTS. A LINKED LIST CAN BE OF THE FOLLOWING TYPES:1-> LINEAR LINKED LIST OR ONE WAY LIST.
2-> DOUBLY LINKED LIST OR TWO WAY LIST.
3-> CIRCULAR LINKED LIST.
4-> HEADER LINKED LIST.
1->LINEAR LINKED LIST:- IN A LINEAR LINKED LIST, ALSO CALLED SINGLY LINKED LIST OR ONE WAY LIST, EACH NODE
IS DIVIDED INTO TWO PARTS: FIRST PART CONTAINS THE INFORMATION OF THE ELEMENT.
SECOND PART, CALLED THE LINK FIELD OR NEXTPOINTER FIELD, CONTAINS THE ADDRESS OF THE NEXT NODE IN
THE LIST.
WE CAN REPRESENT THE LINEAR LINKED LIST AS FOLLOWS:TYPEDEF STRUCT NODE _TYPE
{
INT INFO;
STRUCT NODE_TYPE *NEXT;
}
NODE *START;

THE FOLLOWING OPERATIONS ARE PERFORMED ON LINEAR LINKED LIST.


1->TO CREATE AN EMPTY LIST.
2->TRAVERSING A LIST
3->SEARCHING AN ELEMENT IN THE LIST.
4->INSERTING AN ELEMENT AT THE BEGINNING OF THE LIST.
5-> INSERTING AN ELEMENT AT THE END OF THE LIST.
6-> INSERTING AN ELEMENT AFTER A GIVEN ELEMENT.
7-> DELETING FROM THE BEGINNING OF THE LIST.
8-> DELETING FROM THE END OF THE LIST.
9-> DELETING AFTER A GIVEN ELEMENT OF THE LIST.
10-> REVERSING A LIST.
2->DOUBLY LINKED LIST:- IN

A DOUBLY LINKED LIST, ALSO CALLED SINGLY LINKED LIST OR ONE WAY LIST, EACH

NODE IS DIVIDED INTO TWO PARTS:-

FIRST PART CALLED PREVIOUSPOINTER FIELD, CONTAINS THE ADDRESS OF THE PRECEDING ELEMENT IN THE LIST.
THE SECOND PART CONTAINS THE INFORMATION OF THE ELEMENT.
THE THIRD PART, CALLED THE NEXTPOINTER FIELD, CONTAINS THE ADDRESS OF THE SUCCEEDING ELEMENT IN
THE LIST.

78

WE CAN REPRESENT THE DOUBLY LINKED LIST AS FOLLOWS:typedef struct node_type


{
Struct node_type *prev;
int info;
Struct node_type *next;
}node;
node *head,*tail;

THE FOLLOWING OPERATIONS ARE PERFORMED ON LINEAR LINKED LIST.


1->TO CREATE AN EMPTY LIST.
2->TRAVERSING A LIST
3->SEARCHING AN ELEMENT IN THE LIST.
4->INSERTING AN ELEMENT AT THE BEGINNING OF THE LIST.
5-> INSERTING AN ELEMENT AT THE END OF THE LIST.
6-> INSERTING AN ELEMENT AFTER A GIVEN ELEMENT.
7-> DELETING FROM THE BEGINNING OF THE LIST.
8-> DELETING FROM THE END OF THE LIST.
9-> DELETING AFTER A GIVEN ELEMENT OF THE LIST.
10-> REVERSING A LIST.

THE FOLLOWING ARE THE APPLICATIONS OF LINKED LISTS:1->TO IMPLEMENT OTHER DATA STRUCTURES SUCH AS STACKS, QUEUES, TREES AND GRAPHS.
2->TO MAINTAIN A DIRECTORY OF NAMES.
3->TO PERFORM ARITHMETIC OPERATIONS ON LONG INTEGERS.
4->TO MANIPULATE POLYNOMIALS.
5->TO REPRESENT SPARSE MATRICES.

PROBLEMS
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
(9)
(10)
(11)
(12)
(13)
(14)
(15)

WRITE A MENU DRIVEN PROGRAM TO IMPLEMENT VARIOUS OPERATIONS ON A LINEAR LINKED LIST.
WRITE A PROGRAM FOR INSERTION IN THE ORDERED LINKED LIST
WRITE A PROGRAM FOR MERGING TWO ORDERED LINKED LISTS

WRITE A PROGRAM FOR DELETION OF ALL OCCURANCES OF X FROM LINKED LIST


WRITE A PROGRAM FOR CONCATENATION OF TWO LINKED LISTS
WRITE A PROGRAM FOR SPLITTING THE GIVEN LINKED LIST FROM MID
WRITE A PROGRAM TO REVERSE THE GIVEN LINKED LIST
WRITE A MENU DRIVEN PROGRAM TO IMPLEMENT VARIOUS OPERATIONS ON A CIRCULAR LINKED LIST
PROGRAM FOR CREATING THE ANOTHER COPY OF THE LINKED LIST.
WRITE A FUNCTION TO CONCATENATE TWO CIRCULAR LINKED LIST.
PROGRAM FOR IMPLEMENTATION OF JOSEPHUS PROBLEM
PROGRAM FOR CREATING LINKED LIST BY INTERSECTION OF ELEMENTS OF TWO LINKED LISTS.
PROGRAM FOR CREATING LINKED LIST BY UNION OF ELEMENTS OF TWO LINKED LISTS.
WRITE A MENU DRIVEN PROGRAM TO IMPLEMENT VARIOUS OPERATION ON A DOUBLY LINKEDLIST
WRITE A PROGRAM TO ADD TWO VERY LONG INTEGERS USING LINKED LIST (THE NUMBERS CAN NOT BE STORED
IN INTEGERS & LONG INTEGERS )
(16) WRITE A PROGRAM FOR POLYNOMIAL ADDITION.

79

/****************************************************************/
/* PROG FOR PRIMTIVE OPERATIONS ON LINEAR LINKED LIST */
/* BY: AKHILESH KUMAR SRIVASTAVA */
/* DES: THE IMPLEMENTATION OF LINKED LIST IS STATIC USING ARRAY */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct nodetype
{
int info;
int next;
};
struct nodetype node[100];
int avail;
int list=-1;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void availablelist(void);
int getnode(void);
void freenode(int);
void insbeg(int);
void insafter(int,int);
void insend(int);
int delbeg();
int delafter(int);
int delend();
void traverse();
/****************************************************************/
void main()
{
int p;
int x,c,y;
char ch;
availablelist();
begin:
printf("1. Insert in the beginning\n");
printf("2. Insert after a node\n");
printf("3. Insert in the end\n");
printf("4. Delete from the beginning\n");
printf("5. Delete after a node\n");
printf("6. Delete from the end\n");
printf("7. Traverse\n");
printf("8. exit\n");
printf("===========================\n");
80

printf("Enter your choice\t");


scanf("%d",&c);
switch(c)
{
case 1: printf("\nEnter the element to be inserted");
scanf("%d",&x);
insbeg(x); break;
case 2: printf("\nEnter the element to be inserted after which node");
scanf("%d",&y);
for(p=list;node[p].info!=y&&p!=-1;p=node[p].next)
;
printf("\nEnter the element to be inserted");
scanf("%d",&x);
insafter(p,x); break;
case 3: printf("\nEnter the element to be inserted");
scanf("%d",&x);
insend(x); break;
case 4: printf("The deleted item is:=> %d",delbeg()); break;
case 5: for(p=list;node[p].info!=y&&p!=-1;p=node[p].next)
;
printf("The deleted item is:=> %d",delafter(p)); break;
case 6: printf("The deleted item is:=> %d",delend()); break;
case 7: traverse(); break;
case 8: exit(1);
default: printf("\nWrong choice"); break;
}
printf("Do you wish to continue? (y/n)");
fflush(stdin);
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
goto begin;
}

81

/****************************************************************/
/* Function Definitions */
/****************************************************************/
void availablelist(void)
{
int i;
avail=0;
for(i=0;i<99;i++)
node[i].next=i+1;
node[i].next=-1;
}
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
int getnode(void)
{
int p;
p=avail;
avail=node[avail].next;
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(int p)
{
node[p].next=avail;
avail=p;
}
/****************************************************************/
/***************** Traversing the Linked list ******************/
/****************************************************************/
void traverse()
{
int p=list;
printf("\nThe Linked List is\n");
while(p!=-1)
{
printf("\t%d",node[p].info);
p=node[p].next;
}
}

82

/****************************************************************/
/*Insertion of a node after a node pointed by pointed by pointer p*/
/****************************************************************/
void insafter(int p,int x)
{
int q;
q=getnode();
node[q].info=x;
node[q].next=node[p].next;
node[p].next=q;
}
/****************************************************************/
/**** Insertion of a node in the beginning of the liked list ****/
/****************************************************************/
void insbeg(int x)
{
int p;
p=getnode();
node[p].info=x;
node[p].next=list;
list=p;
}
/****************************************************************/
/******* Insertion of a node in the end of the liked list *******/
/****************************************************************/
void insend(int x)
{
int p=list,q;
q=getnode();
node[q].info=x;
node[q].next=-1;
while(node[p].next!=-1)
p=node[p].next;
node[p].next=q;
}
/****************************************************************/
/**** deletion of a node from the beginning of the liked list ***/
/****************************************************************/
int delbeg()
{
int p;
int x;
p=list;
list=node[p].next;
x=node[p].info;
freenode(p);
return x;
}
/****************************************************************/
83

/*deletion of a node after a node pointed by pointed by pointer p*/


/****************************************************************/
int delafter(int p)
{
int q;
int x;
q=node[p].next;
node[q].next=node[p].next;
x=node[p].info;
freenode(p);
return x;
}
/****************************************************************/
/******* Deletion of a node from the end of the liked list ******/
/****************************************************************/
int delend()
{
int p=list,q=-1;
int x;
while(node[p].next!=-1)
{
q=p;
p=node[p].next;
}
node[q].next=-1;
x=node[p].info;
freenode(p);
node[q].next=-1;
return x;
}
/****************************************************************/

84

Output:
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
1
Enter the element to be inserted100
Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
3
Enter the element to be inserted200
Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
7
The Linked List is
100 200Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
2
85

Enter the element to be inserted after which node100


Enter the element to be inserted300
Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
7
The Linked List is
100 300 200Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
4
The deleted item is:=> 100Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
6
The deleted item is:=> 200Do you wish to continue? (y/n)

86

/****************************************************************/
/* PROG FOR PRIMTIVE OPERATIONS ON LINEAR LINKED LIST */
/* BY: AKHILESH KUMAR SRIVASTAVA */
/* DES: THE IMPLEMENTATION OF LINKED LIST IS DYNAMICALLY */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
int info;
struct node *next;
};
typedef struct node* NODEPTR;
/****************************************************************/
/**************** Global initialisation of Linked List **********/
NODEPTR list=NULL;
/****************************************************************/
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void insbeg(int);
void insafter(int,int);
void insend(int);
int delbeg();
int delafter(int);
int delend();
void traverse();
/****************************************************************/
void main()
{
NODEPTR p;
int x,c,y;
char ch;
begin:
printf("1. Insert in the beginning\n");
printf("2. Insert after a node\n");
printf("3. Insert in the end\n");
printf("4. Delete from the beginning\n");
printf("5. Delete after a node\n");
printf("6. Delete from the end\n");
printf("7. Traverse\n");
printf("8. exit\n");
87

printf("===========================\n");
printf("Enter your choice\t");
scanf("%d",&c);
switch(c)
{
case 1: printf("\nEnter the element to be inserted");
scanf("%d",&x);
insbeg(x); break;
case 2: printf("\nEnter the element to be inserted after which node");
scanf("%d",&y);
printf("\nEnter the element to be inserted");
scanf("%d",&x);
insafter(y,x); break;
case 3: printf("\nEnter the element to be inserted");
scanf("%d",&x);
insend(x); break;
case 4: printf("The deleted item is:=> %d",delbeg()); break;
case 5: printf("\nEnter the element to be inserted after which node");
scanf("%d",&y);
printf("The deleted item is:=> %d",delafter(y)); break;
case 6: printf("The deleted item is:=> %d",delend()); break;
case 7: traverse(); break;
case 8: exit(1);
default: printf("\nWrong choice"); break;
}
printf("Do you wish to continue? (y/n)");
fflush(stdin);
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
goto begin;
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
88

}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Traversing the Linked list ******************/
/****************************************************************/
void traverse()
{
NODEPTR p=list;
printf("\nThe Linked List is\n");
while(p!=NULL)
{
printf("\t%d",p->info);
p=p->next;
}
}
/****************************************************************/
/*Insertion of a node after a node pointed by pointed by pointer p*/
/****************************************************************/
void insafter(int y,int x)
{
NODEPTR p,q;
q=getnode();
q->info=x;
for(p=list;p->info!=y&&p!=NULL;p=p->next)
;
q->next=p->next;
p->next=q;
}
/****************************************************************/
/**** Insertion of a node in the beginning of the liked list ****/
/****************************************************************/
void insbeg(int x)
{
NODEPTR p;
p=getnode();
p->info=x;
p->next=list;
list=p;
}
/****************************************************************/
/******* Insertion of a node in the end of the liked list *******/
/****************************************************************/
void insend(int x)
{
89

NODEPTR p=list,q;
q=getnode();
q->info=x;
q->next=NULL;
while(p->next!=NULL)
p=p->next;
p->next=q;
}
/****************************************************************/
/**** deletion of a node from the beginning of the liked list ***/
/****************************************************************/
int delbeg()
{
NODEPTR p;
int x;
p=list;
list=p->next;
x=p->info;
freenode(p);
return x;
}
/****************************************************************/
/*deletion of a node after a node pointed by pointed by pointer p*/
/****************************************************************/
int delafter(int y)
{
NODEPTR p=list,q;
int x;
for(p=list;p->info!=y&&p!=NULL;p=p->next)
;
q=p->next;
q->next=p->next;
x=p->info;
freenode(p);
return x;
}
/****************************************************************/
/******* Deletion of a node from the end of the liked list ******/
/****************************************************************/
int delend()
{
NODEPTR p=list,q=NULL;
int x;
while(p->next!=NULL)
{
q=p;
p=p->next;
}
q->next=NULL;
90

x=p->info;
freenode(p);
q->next=NULL;
return x;
}
/****************************************************************/

Output:
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
1
Enter the element to be inserted100
Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
3
Enter the element to be inserted200
Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
7
The Linked List is
100 200Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
91

5. Delete after a node


6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
2
Enter the element to be inserted after which node100
Enter the element to be inserted300
Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
7
The Linked List is
100 300 200Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
4
The deleted item is:=> 100Do you wish to continue? (y/n)y
1. Insert in the beginning
2. Insert after a node
3. Insert in the end
4. Delete from the beginning
5. Delete after a node
6. Delete from the end
7. Traverse
8. exit
===========================
Enter your choice
6
The deleted item is:=> 200Do you wish to continue? (y/n)

92

/****************************************************************/
/* Prog for insertion in an ordered linked lists */
/* By: Akhilesh Kumar Srivastava */
/* Des: The implementation of linked list is dynamically */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
int info;
struct node *next;
};
typedef struct node* NODEPTR;
/****************************************************************/
/**************** Global initialisation of Linked List **********/
NODEPTR list=NULL;
/****************************************************************/
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void insbeg(int);
void insafter(int,int);
void insend(int);
int delbeg();
int delafter(int);
int delend();
void traverse();
/****************************************************************/
void main()
{
NODEPTR p,q=NULL;
int x;
clrscr();
insbeg(100);
insbeg(90);
insbeg(70);
insbeg(50);
insbeg(30);
traverse();
printf("\nEnter your Item to be inserted");
scanf("%d",&x);
p=list;
while(x>=p->info&&p!=NULL)
{
93

q=p;
p=p->next;
}
if(q==NULL)
insbeg(x);
else
insafter(q->info,x);
traverse();
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Traversing the Linked list ******************/
/****************************************************************/
void traverse()
{
NODEPTR p=list;
printf("\nThe Linked List is\n");
while(p!=NULL)
{
printf("\t%d",p->info);
p=p->next;
}
}

94

/****************************************************************/
/*Insertion of a node after a node pointed by pointed by pointer p*/
/****************************************************************/
void insafter(int y,int x)
{
NODEPTR p,q;
q=getnode();
q->info=x;
for(p=list;p->info!=y&&p!=NULL;p=p->next)
;
q->next=p->next;
p->next=q;
}
/****************************************************************/
/**** Insertion of a node in the beginning of the liked list ****/
/****************************************************************/
void insbeg(int x)
{
NODEPTR p;
p=getnode();
p->info=x;
p->next=list;
list=p;
}
/****************************************************************/

Output
The Linked List is
30 50 70 90 100
Enter your Item to be inserted20
The Linked List is
20 30 50 70 90 100
The Linked List is
30 50 70 90 100
Enter your Item to be inserted60
The Linked List is
30 50 60

70

90

100

The Linked List is


30 50 70 90 100
Enter your Item to be inserted110
The Linked List is
30 50 70

90

100

110

95

/****************************************************************/
/* Prog for merging two ordered linked lists */
/* By: Akhilesh Kumar Srivastava */
/* Des: The implementation of linked list is dynamically */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
int info;
struct node *next;
};
typedef struct node* NODEPTR;
/****************************************************************/
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void insend(NODEPTR*,int);
void traverse();
/****************************************************************/
void main()
{
NODEPTR list1=NULL,list2=NULL,list3=NULL;
NODEPTR p,q;
int n1,n2,x,i;
clrscr();
printf("\nEnter the no of elements in first ordered list:=>\t");
scanf("%d",&n1);
printf("Enter the elements");
for(i=0;i<n1;i++)
{
scanf("%d",&x);
insend(&list1,x);
}
printf("\nThe First List is:=>\t");
traverse(list1);
printf("\nEnter the no of elements in second ordered list:=>\t");
scanf("%d",&n2);
printf("Enter the elements");
for(i=0;i<n2;i++)
{
scanf("%d",&x);
insend(&list2,x);
}
printf("\nThe Second List is:=>\t");
96

traverse(list2);
p=list1; q=list2;
while(p!=NULL&&q!=NULL)
{
if(p->info<q->info)
{
insend(&list3,p->info);
p=p->next;
}
else
{
insend(&list3,q->info);
q=q->next;
}
}
while(p!=NULL)
{
insend(&list3,p->info);
p=p->next;
}
while(q!=NULL)
{
insend(&list3,q->info);
q=q->next;
}
printf("\nThe ordered list is:=>\t");
traverse(list3);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Traversing the Linked list ******************/
97

/****************************************************************/
void traverse(NODEPTR list)
{
NODEPTR p=list;
while(p!=NULL)
{
printf("\t%d",p->info);
p=p->next;
}
}
/****************************************************************/
/******* Insertion of a node in the end of the liked list *******/
/****************************************************************/
void insend(NODEPTR *list,int x)
{
NODEPTR p=*list,q;
q=getnode();
q->info=x;
q->next=NULL;
if(*list==NULL)
*list=q;
else
{
while(p->next!=NULL)
p=p->next;
p->next=q;
}
}
/****************************************************************/

OUTPUT
ENTER THE NO OF ELEMENTS IN FIRST ORDERED LIST:=>
ENTER THE ELEMENTS100 200 300 400 500
THE FIRST LIST IS:=>

100

200

300

400

ENTER THE NO OF ELEMENTS IN SECOND ORDERED LIST:=>


ENTER THE ELEMENTS50 70 150 250
THE SECOND LIST IS:=>

50

70

150

250

THE ORDERED LIST IS:=>

50

70

100

150

5
500
4

200

250

300

400

500

98

/****************************************************************/
/* PROG FOR PRIMTIVE OPERATIONS ON CIRCULAR LINKED LIST */
/* BY: AKHILESH KUMAR SRIVASTAVA */
/* DES: THE IMPLEMENTATION OF LINKED LIST IS DYNAMICALLY */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
int info;
struct node *next;
};
typedef struct node* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void insbeg(NODEPTR*,int);
void insafter(NODEPTR*,int);
void insend(NODEPTR*,int);
int delbeg(NODEPTR*);
int delafter(NODEPTR*);
int delend(NODEPTR*);
void traverse(NODEPTR);
/****************************************************************/
void main()
{
NODEPTR list=NULL;
NODEPTR p;
int x,c,y;
char ch;
begin:
printf("1. Insert in the beginning\n");
printf("2. Insert after a node\n");
printf("3. Insert in the end\n");
printf("4. Delete from the beginning\n");
printf("5. Delete after a node\n");
printf("6. Delete from the end\n");
printf("7. Traverse\n");
printf("8. exit\n");
printf("===========================\n");
printf("Enter your choice\t");
scanf("%d",&c);
switch(c)
{
99

case 1: printf("\nEnter the element to be inserted");


scanf("%d",&x);
insbeg(&list,x); break;
case 2: printf("\nEnter the element to be inserted after which node");
scanf("%d",&y);
for(p=list;p->info!=y&&p!=NULL;p=p->next)
;
printf("\nEnter the element to be inserted");
scanf("%d",&x);
insafter(&p,x); break;
case 3: printf("\nEnter the element to be inserted");
scanf("%d",&x);
insend(&list,x); break;
case 4: printf("The deleted item is:=> %d",delbeg(&list)); break;
case 5: for(p=list;p->info!=y&&p!=NULL;p=p->next)
;
printf("The deleted item is:=> %d",delafter(&list)); break;
case 6: printf("The deleted item is:=> %d",delend(&list)); break;
case 7: traverse(list); break;
case 8: exit(1);
default: printf("\nWrong choice"); break;
}
printf("Do you wish to continue? (y/n)");
fflush(stdin);
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
goto begin;
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Traversing the Linked list ******************/
/****************************************************************/
100

void traverse(NODEPTR p)
{
printf("\nThe Linked List is\n");
while(p!=NULL)
{
printf("\t%d",p->info);
p=p->next;
}
}
/****************************************************************/
/*Insertion of a node after a node pointed by pointed by pointer p*/
/****************************************************************/
void insafter(NODEPTR *p,int x)
{
NODEPTR q;
q=getnode();
q->info=x;
q->next=(*p)->next;
(*p)->next=q;
}
/****************************************************************/
/**** Insertion of a node in the beginning of the liked list ****/
/****************************************************************/
void insbeg(NODEPTR *list,int x)
{
NODEPTR p,q;
p=getnode();
p->info=x;
p->next=(*list)->next;
(*list)->next=p;
}
/****************************************************************/
/******* Insertion of a node in the end of the liked list *******/
/****************************************************************/
void insend(NODEPTR *list,int x)
{
NODEPTR q;
q=getnode();
q->info=x;
q->next=(*list)->next;
(*list)->next=q;
(*list)=q;
}
/****************************************************************/
/**** deletion of a node from the beginning of the liked list ***/
/****************************************************************/
int delbeg(NODEPTR *list)
{
NODEPTR p;
int x;
101

p=(*list)->next;
(*list)->next=p->next;
x=p->info;
freenode(p);
return x;
}
/****************************************************************/
/*deletion of a node after a node pointed by pointed by pointer p*/
/****************************************************************/
int delafter(NODEPTR *p)
{
NODEPTR q;
int x;
q=(*p)->next;
q->next=(*p)->next;
x=(*p)->info;
freenode(*p);
return x;
}
/****************************************************************/
/******* Deletion of a node from the end of the liked list ******/
/****************************************************************/
int delend(NODEPTR *list)
{
NODEPTR p=*list,q,r;
int x;
while(p->next!=*list)
{
p=p->next;
}
p->next=(*list)->next;
x=(*list)->info;
r=(*list);
*list=p;
freenode(r);
return x;
}
/****************************************************************/

102

/****************************************************************/
/*** Prog for addition of very long integers using Linked List***/
/*** By: Akhilesh Kumar Srivastava ***/
/*** Des: The implementation of the linked list is dynamically **/
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
int info;
struct node *next;
};
typedef struct node* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void insend(NODEPTR*,int);
int delend(NODEPTR*);
void addlist(NODEPTR,NODEPTR);
void traverse(NODEPTR);
/****************************************************************/
void main()
{
NODEPTR list1=NULL,list2=NULL;
char x[20],y[20];
int n,i1,i2,i,j;
clrscr();
printf("Enter the first no.:=>\n");
scanf("%s",x);
printf("Enter the second no.:=>\n");
scanf("%s",y);
i1=strlen(x);
i2=strlen(y);
for(i=i1-1;i>=0;i=i-4)
{
n=0;
if(i>=3)
{
for(j=i-3;j<=i;j++)
n=n*10+(x[j]-'0');
}
else
{
for(j=0;j<=i;j++)
n=n*10+(x[j]-'0');
103

}
insend(&list1,n);
}
traverse(list1);
for(i=i2-1;i>=0;i=i-4)
{
n=0;
if(i>=3)
{
for(j=i-3;j<=i;j++)
n=n*10+(y[j]-'0');
}
else
{
for(j=0;j<=i;j++)
n=n*10+(y[j]-'0');
}
insend(&list2,n);
}
traverse(list2);
addlist(list1,list2);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/******* Insertion of a node in the end of the liked list *******/
/****************************************************************/
void insend(NODEPTR*list,int x)
{
NODEPTR p=*list,q;
q=getnode();
104

q->info=x;
q->next=NULL;
if(p==NULL)
*list=q;
else
{
while(p->next!=NULL)
p=p->next;
p->next=q;
}
}
/****************************************************************/
/******* Deletion of a node from the end of the liked list ******/
/****************************************************************/
int delend(NODEPTR *list)
{
NODEPTR p=*list,q=NULL;
int x;
while(p->next!=NULL)
{
q=p;
p=p->next;
}
if(q!=NULL)
{
q->next=NULL;
}
else
{
*list=NULL;
}
x=p->info;
freenode(p);
return x;
}
/****************************************************************/
/********** Adding the contents of the two Linked Lists *********/
/****************************************************************/
void addlist(NODEPTR list1,NODEPTR list2)
{
int total,sum,carry=0;
NODEPTR list=NULL;
while(list1!=NULL&&list2!=NULL)
{
total=list1->info+list2->info+carry;
sum=total%10000;
carry=total/10000;
insend(&list,sum);
list1=list1->next;
list2=list2->next;
105

}
while(list1!=NULL)
{
total=list1->info+carry;
sum=total%10000;
carry=total/10000;
insend(&list,sum);
list1=list1->next;
}
while(list2!=NULL)
{
total=list2->info+carry;
sum=total%10000;
carry=total/10000;
insend(&list,sum);
list2=list2->next;
}
if(carry==1)
insend(&list,carry);
printf("\n\nThe sum is:=>\t");
while(list!=NULL)
{
printf("%d",delend(&list));
}
}
/****************************************************************/
/************* Travesring the Linked List ***********************/
/****************************************************************/
void traverse(NODEPTR p)
{
printf("\nThe Linked List is\n");
while(p!=NULL)
{
printf("\t%d",p->info);
p=p->next;
}
}
/****************************************************************/

106

Output
Enter the first no.:=>
123456789123456789
Enter the second no.:=>
17896582365475
The Linked List is
6789 2345 7891 3456 12
The Linked List is
5475 8236 8965 17
The sum is:=> 12347468575822264
Enter the first no.:=>
12356456465321215
Enter the second no.:=>
21231584986513
The Linked List is
1215 6532 4564 2356 1
The Linked List is
6513 8498 2315 21
The sum is:=> 12377688050307728

107

/*******************************************************************/
/* Prog for addition of addition of 2 polynomials using Linked List*/
/*** By: Akhilesh Kumar Srivastava ***/
/*** Des: The implementation of the linked list is dynamically *****/
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
int coef;
int exp;
struct node *next;
};
typedef struct node* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void insend(NODEPTR*,int,int);
void addpoly(NODEPTR,NODEPTR);
void traverse(NODEPTR);
/****************************************************************/
void main()
{
NODEPTR poly1=NULL,poly2=NULL;
int x,y,c,e,i;
clrscr();
printf("Enter the no.of terms in first Polynomial:=> \t");
scanf("%d",&x);
printf("Enter the no.of terms in second Polynomial:=> \t");
scanf("%d",&y);
printf("\n\nEnter the First Polynaomial:=>\n");
for(i=0;i<x;i++)
{
printf("Enter the coef & exp of the %dth term",i+1);
scanf("%d%d",&c,&e);
insend(&poly1,c,e);
}
traverse(poly1);
printf("\nEnter the Second Polynaomial:=>\n");
for(i=0;i<y;i++)
{
printf("Enter the coef & exp of the %dth term",i+1);
scanf("%d%d",&c,&e);
insend(&poly2,c,e);
108

}
traverse(poly2);
addpoly(poly1,poly2);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
}
/****************************************************************/
/******* Insertion of a node in the end of the liked list *******/
/****************************************************************/
void insend(NODEPTR*list,int x,int y)
{
NODEPTR p=*list,q;
q=getnode();
q->coef=x;
q->exp=y;
q->next=NULL;
if(p==NULL)
*list=q;
else
{
while(p->next!=NULL)
p=p->next;
p->next=q;
}
}
/****************************************************************/
/********** Adding the contents of the two Polynomials **********/
/****************************************************************/
void addpoly(NODEPTR list1,NODEPTR list2)
{
NODEPTR list=NULL;
while(list1!=NULL&&list2!=NULL)
{
if(list1->exp==list2->exp)
{
insend(&list,list1->coef+list2->coef,list1->exp);
list1=list1->next;
list2=list2->next;
109

}
else
{
if(list1->exp>list2->exp)
{
insend(&list,list1->coef,list1->exp);
list1=list1->next;
}
if(list1->exp<list2->exp)
{
insend(&list,list2->coef,list2->exp);
list2=list2->next;
}
}
}
while(list1!=NULL)
{
insend(&list,list1->coef,list1->exp);
list1=list1->next;
}
while(list2!=NULL)
{
insend(&list,list2->coef,list2->exp);
list2=list2->next;
}
printf("\tThe resultant polynomial is:=>\t");
traverse(list);
}
/****************************************************************/
/************* Travesring the Linked List ***********************/
/****************************************************************/
void traverse(NODEPTR p)
{
printf("\nThe Linked List is\n");
while(p!=NULL)
{
printf("%d",p->coef);
printf("x%d + ",p->exp);
p=p->next;
}
}
/****************************************************************/

110

Output
Enter the no.of terms in first Polynomial:=> 4
Enter the no.of terms in second Polynomial:=> 4
Enter the First Polynaomial:=>
Enter the coef & exp of the 1th term9 7
Enter the coef & exp of the 2th term5 6
Enter the coef & exp of the 3th term-4 2
Enter the coef & exp of the 4th term8 0
The Linked List is
9x7 + 5x6 + -4x2 + 8x0 +
Enter the Second Polynaomial:=>
Enter the coef & exp of the 1th term-8 5
Enter the coef & exp of the 2th term6 6
Enter the coef & exp of the 3th term2 2
Enter the coef & exp of the 4th term-5 0
The Linked List is
-8x5 + 6x6 + 2x2 + -5x0 +
The resultant polynomial is:=>
The Linked List is
9x7 + 5x6 + -8x5 + 6x6 + -2x2 + 3x0 +

Enter the no.of terms in first Polynomial:=> 5


Enter the no.of terms in second Polynomial:=> 3
Enter the First Polynaomial:=>
Enter the coef & exp of the 1th term6 9
Enter the coef & exp of the 2th term5 8
Enter the coef & exp of the 3th term-7 3
Enter the coef & exp of the 4th term5 2
Enter the coef & exp of the 5th term6 0
The Linked List is
6x9 + 5x8 + -7x3 + 5x2 + 6x0 +
Enter the Second Polynaomial:=>
Enter the coef & exp of the 1th term8 8
Enter the coef & exp of the 2th term4 3
Enter the coef & exp of the 3th term-2 0
The Linked List is
8x8 + 4x3 + -2x0 + The resultant polynomial is:=>
The Linked List is
6x9 + 13x8 + -3x3 + 5x2 + 4x0 +
111

/****************************************************************/
/******* Prog for concatenation of two Linear Linked Lists ******/
/****************** By: Akhilesh Kumar Srivastava ***************/
/***** Des: The implementation of linked list is dynamically ****/
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
int info;
struct node *next;
};
typedef struct node* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void insend(NODEPTR*,int);
void traverse(NODEPTR);
/****************************************************************/
void main()
{
NODEPTR list1=NULL,list2=NULL,list3=NULL;
NODEPTR p;
int i,n1,n2,x;
printf("\nEnter the no of elements in first list:=> ");
scanf("%d",&n1);
printf("\nEnter the elements of first linked list:=> ");
for(i=0;i<n1;i++)
{
scanf("%d",&x);
insend(&list1,x);
}
printf("Enter the no of elements in first list:=> ");
scanf("%d",&n2);
printf("\nEnter the elements of first linked list:=> ");
for(i=0;i<n2;i++)
{
scanf("%d",&x);
insend(&list2,x);
}
if(list1==NULL&&list2==NULL)
list3=NULL;
else
112

{
if(list1==NULL)
list3=list2;
else
{
if(list2==NULL)
list3=list1;
else
{
p=list1;
list3=list1;
while(p->next!=NULL)
p=p->next;
p->next=list2;
}
}
}
printf("\nThe Concatenated list is:=>\t");
traverse(list3);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Traversing the Linked list ******************/
/****************************************************************/
void traverse(NODEPTR p)
{
printf(\n);
while(p!=NULL)
{
printf("\t%d",p->info);
p=p->next;
113

}
}
/****************************************************************/
/******* Insertion of a node in the end of the liked list *******/
/****************************************************************/
void insend(NODEPTR *list,int x)
{
NODEPTR p=*list,q;
q=getnode();
q->info=x;
q->next=NULL;
if(*list==NULL)
*list=q;
else
{
while(p->next!=NULL)
p=p->next;
p->next=q;
}
}
/****************************************************************/

Output:
Enter the no of elements in first list:=> 5
Enter the elements of first linked list:=> 100 200 300 520 150
Enter the no of elements in first list:=> 6
Enter the elements of first linked list:=> 10 20 30 25 35 60
The Concatenated list is:=>
100 200 300 520

150

10

20

30

25

35

60

114

/****************************************************************/
/******* Prog for Splitting the given Linear Linked Lists *******/
/****************** By: Akhilesh Kumar Srivastava ***************/
/***** Des: The implementation of linked list is dynamically ****/
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
int info;
struct node *next;
};
typedef struct node* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void insend(NODEPTR*,int);
void traverse(NODEPTR);
/****************************************************************/
void main()
{
NODEPTR list=NULL,list1=NULL,list2=NULL;
NODEPTR p;
int i,n,x,count=0;
printf("\nEnter the no of elements in the list:=> ");
scanf("%d",&n);
printf("\nEnter the elements of first linked list:=> ");
for(i=0;i<n;i++)
{
scanf("%d",&x);
insend(&list,x);
}
p=list;
while(p!=NULL)
{
count++;
p=p->next;
}
printf("\n%d",count);
i=1;
p=list;
list1=list;
while(i<(count/2))
{
p=p->next;
i++;
}
list2=p->next;
p->next=NULL;
printf("\nThe First list is:=>\t");
traverse(list1);
printf("\nThe First list is:=>\t");
traverse(list2);

115

getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Traversing the Linked list ******************/
/****************************************************************/
void traverse(NODEPTR p)
{
while(p!=NULL)
{
printf("\t%d",p->info);
p=p->next;
}
}
/****************************************************************/
/******* Insertion of a node in the end of the liked list *******/
/****************************************************************/
void insend(NODEPTR *list,int x)
{
NODEPTR p=*list,q;
q=getnode();
q->info=x;
q->next=NULL;
if(*list==NULL)
*list=q;
else
{
while(p->next!=NULL)
p=p->next;
p->next=q;
}
}
/****************************************************************/

116

Output:->
---------Enter the no of elements in the list:=> 10
Enter the elements of first linked list:=> 100
200
300
400
500
600
700
800
900
999
10
The First list is:=>
100
200
300
400
500
The First list is:=>
600
700
800
900
999
--------------------------------------------------------------------Enter the no of elements in the list:=> 7
Enter the elements of first linked list:=> 100
200
300
400
500
600
700
7
The First list is:=>
The First list is:=>

100
400

200
500

300
600

700

117

/****************************************************************/
/* Program to reverse the given Linear Linked List */
/* By: Akhilesh Kumar Srivastava */
/* Des: The implementation of linked list is dynamically */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
int info;
struct node *next;
};
typedef struct node* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void insbeg(NODEPTR*,int);
void insend(NODEPTR*,int);
int delbeg(NODEPTR*);
void traverse(NODEPTR);
/****************************************************************/
void main()
{
NODEPTR list1=NULL,list2=NULL;
int x,i,n;
printf("\nEnter the no of elements in the list:=> ");
scanf("%d",&n);
printf("\nEnter the elements of linked list:=> ");
for(i=0;i<n;i++)
{
scanf("%d",&x);
insend(&list1,x);
}
printf("\nThe given linked list is");
traverse(list1);
while(list1!=NULL)
{
x=delbeg(&list1);
insbeg(&list2,x);
}
printf("\nThe reversed linked list is:=>\n");
traverse(list2);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;

118

}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Traversing the Linked list ******************/
/****************************************************************/
void traverse(NODEPTR p)
{
while(p!=NULL)
{
printf("\t%d",p->info);
p=p->next;
}
}
/****************************************************************/
/**** Insertion of a node in the beginning of the liked list ****/
/****************************************************************/
void insbeg(NODEPTR *list,int x)
{
NODEPTR p;
p=getnode();
p->info=x;
p->next=*list;
*list=p;
}
/****************************************************************/
/******* Insertion of a node in the end of the liked list *******/
/****************************************************************/
void insend(NODEPTR *list,int x)
{
NODEPTR p=*list,q;
q=getnode();
q->info=x;
q->next=NULL;
if(*list==NULL)
*list=q;
else
{
while(p->next!=NULL)
p=p->next;
p->next=q;
}
}
/****************************************************************/
/**** deletion of a node from the beginning of the liked list ***/
/****************************************************************/
int delbeg(NODEPTR *list)
{
NODEPTR p;
int x;
p=*list;
*list=p->next;
x=p->info;
freenode(p);
return x;
}

119

/****************************************************************/
Output:->
--------Enter the no of elements in the list:=> 5
Enter the elements of linked list:=> 100
200
300
400
500
The given linked list is
The reversed linked list is:=>

100
500

200
400

300
300

400
200

500
100

120

ASSIGNMENT NO. 7
OBJECT:-

IMPLEMENT THE VARIOUS SEARCHING ALGORITHMS

THEORY AND CONCEPTS:SEARCHING

IS THE PROCESS OF FINDING THE LOCATION OF GIVEN ELEMENT IN THE LINEAR ARRAY.

THE SEARCH

IS SAID

TO BE SUCCESSFUL IF THE GIVEN ELEMENT IS FOUND I.E. THE ELEMENT DOES EXISTS IN THE ARRAY; OTHERWISE
UNSUCCESSFUL .

THERE ARE TWO APPROACHES TO SEARCH OPERATION: LINEAR SEARCH


BINARY SEARCH
LINEAR SEARCH:GIVEN

NO INFORMATION ABOUT THE ARRAY A, THE ONLY WAY TO SEARCH FOR GIVEN ELEMENT ITEM IS TO COMPARE

ITEM WITH EACH ELEMENT OF A ONE BY ONE.

THIS
CALLED LINEAR SEARCH OR SEQUENTIAL SEARCH.

METHOD, WHICH TRAVERSES A SEQUENTIALLY TO LOCATE ITEM IS

BINARY SEARCH:SUPPOSE

THE ELEMENTS OF THE ARRAY

ARE SORTED IN ASCENDING ORDER( IF THE ELEMENTS ARE NUMBERS ) OR

DICTIONARY ORDER( IF THE ELEMENTS ARE STRINGS).

THE BEST SEARCHING ALGORITHM, CALLED BINARY SEARCH, IS


WE DO USE THIS APPROACH IN OUR DAILY LIFE. FOR EXAMPLE,
SUPPOSE WE WANT TO FIND THE MEANING OF THE TERM MODEM IN A COMPUTER DICTIONARY . OBVIOUSLY, WE DONT
SEARCH PAGE BY PAGE. WE OPEN THE DICTIONARY IN THE MIDDLE (ROUGHLY) TO DETERMINE WHICH HALF CONTAINS
THE TERM BEING SOUGHT. THEN FOR THE SUBSEQUENT SEARCH ONE HALF IS DISCARDED , AND WE SEARCH IN THE OTHER
HALF. THIS PROCESS IS CONTINUED TILL OTHER WE HAVE LOCATED THE REQUIRED TERM OR THAT TERM IS MISSING FROM
THE DICTIONARY , WHICH WILL INDICATED BY THE FACT THAT AT THE END WE WILL BE LEFT WITH ONLY ONE PAGE.
USED TO FIND THE LOCATION OF THE GIVEN ELEMENT .

PROBLEMS :(1) WRITE A PROGRAM TO INPUT HOW MANY NUMBERS AND THEN INPUT THE NUMBERS AND THEN SEARCH ANY NUMBER
WITH THE HELP OF SEQUENTIAL /LINEAR SEARCH .
(2) WRITE A PROGRAM TO INPUT HOW MANY NUMBERS AND THEN INPUT THE NUMBERS AND THEN SEARCH ANY NUMBER
WITH THE HELP OF BINARY SEARCH .
(3) WRITE A PROGRAM TO INPUT HOW MANY NUMBERS AND THEN INPUT THE NUMBERS AND THEN SEARCH ANY NUMBER
WITH THE HELP OF INDEX SEQUENTIAL SEARCH .

121

/****************************************************************/
/* PROGRAM FOR SEQUENTIAL SEARCH
*/
/* BY: AKHILESH KUMAR SRIVASTAVA
*/
/* DES: THIS IS O(N) ALGO IN AVG,WORST CASE & O(1) IN BEST CASE */
/****************************************************************/
/************* Global declaration of Array *********************/
int a[10]={5,10,15,20,6,7,3,55,9,2};
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
int seq_search(int,int,int);
/****************************************************************/
void main()
{
int x,y;
printf("\nenter the element to be searched");
scanf("%d",&x);
y=seq_search(0,9,x);
if(y>=0)
printf("Element %d is present at %d location in the array",x,y+1);
else
printf("Element isnot present in the array");
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
int seq_search(int low,int high,int x)
{
int i;
for(i=low;i<=high;i++)
{
if(a[i]==x)
return i;
}
return -1;
}
/****************************************************************/
Output->
-------enter the element to be searched30
Element isnot present in the array
enter the element to be searched9
Element 9 is present at 9 location in the array

enter the element to be searched15


Element 15 is present at 3 location in the array

122

/****************************************************************/
/* PROGRAM FOR BINARY SEARCH ITERATIVELY */
/* BY: AKHILESH KUMAR SRIVASTAVA
*/
/* DES: THIS IS O(LOGN) ALGO AVERAGE CASE AND O(1) IN BEST CASE */
/****************************************************************/
#include<stdio.h>
#include<conio.h>
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
int binary_search(int[],int,int);
/****************************************************************/
void main()
{
int a[10]={2,4,6,8,10,12,14,16,18,20};
int x,n,y;
printf("\nEnter the element to be searched");
scanf("%d",&x);
y=binary_search(a,10,x);
if(y==-1)
printf("\nThe element is not present in the array");
else
printf("\nThe element is present at %d location in the array",y+1);
getch();
}
/****************************************************************/
/* Function Definition */
/****************************************************************/
int binary_search(int a[],int n,int x)
{
int low=0;
int high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==x)
return mid;
else
{
if(x<a[mid])
high=mid-1;
else
low=mid+1;
}
}
return (-1);
}
/*********************************************/
Output->
-------Enter the element to be searched10
The element is present at 5 location in the array
Enter the element to be searched12
The element is present at 6 location in the array
Enter the element to be searched17

The element is not present in the array


123

ASSIGNMENT NO. 8
OBJECT:-

IMPLEMENTATION OF VARIOUS SORTING ALGORITHMS

THEORY AND CONCEPTS:SORTING

IS THE PROCESS OF ARRANGING THE ELEMENTS IN SOME LOGICAL ORDER.

THIS

LOGICAL ORDER MAY BE

ASCENDING OR DESCENDING IN CASE OF NUMERIC VALUES OR DICTIONARY ORDER IN CASE OF ALPHANUMERIC VALUES

THE FOLLOWING ARE THE SORTING TECHNIQUES: BUBBLE SORT


SELECTION SORT
INSERTION SORT
MERGE SORT
QUICK SORT
HEAP SORT.
RADIX SORT
SHELL SORT
PROBLEMS :WRITE A PROGRAM FOR ALL THE SORTING TECHNIQUES.

124

/****************************************************************/
/* Program for Bubble Sort
*/
/* By: Akhilesh Kumar Srivastava
*/
/* Des: This is O(n2) Algo in AVG & WORST case & O(n) in BEST case */
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void bubble_sort(int[],int);
/****************************************************************/
void main()
{
int a[20],n,i;
clrscr();
printf("Enter the no of elements in the array");
scanf("%d",&n);
printf("Enter the array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
bubble_sort(a,n);
printf("\nThe sorted set is:=>\n");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
getch();
}
/****************************************************************/
/* Function Definition */
/****************************************************************/
void bubble_sort(int a[],int n)
{
int i,j,t;
char comp='t';
for(i=0;i<n-1&&comp=='t';i++)
{
comp='f';
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
comp='t';
}
}
}
}
/****************************************************************/
Output->
-------Enter the no of elements in the array 7
Enter the array elements 10 9 6 7 3 2 1
The sorted set is:=>
1
2

10

125

/*********
*******************************************************/
/* Program for Selection Sort
*/
/* By: Akhilesh Kumar Srivastava
*/
/* Des: This is O(n2) Algo in all three case */
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void selection_sort(int[],int);
/****************************************************************/
void main()
{
int a[20],n,i;
printf("Enter the no of elements in the array");
scanf("%d",&n);
printf("Enter the array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
selection_sort(a,n);
printf("\nThe sorted set is:=>\n");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
getch();
}
/****************************************************************/
/* Function Definition */
/****************************************************************/
void selection_sort(int a[],int n)
{
int i,j,t;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n-1;j++)
{
if(a[j]<a[i])
{
t=a[j];
a[j]=a[i];
a[i]=t;
}
}
}
}
/****************************************************************/
Output->
-------Enter the no of elements in the array 7
Enter the array elements 10 9 6 7 3 2 1
The sorted set is:=>

126

10

/****************************************************************/
/* Program for Insertion Sort
*/
/* By: Akhilesh Kumar Srivastava
*/
/* Des: This is O(n2) Algo in AVG & WORST case & O(n) in BEST case */
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void insertion_sort(int[],int);
/****************************************************************/
void main()
{
int a[20],n,i;
printf("Enter the no of elements in the array");
scanf("%d",&n);
printf("Enter the array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
insertion_sort(a,n);
printf("\nThe sorted set is:=>");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
void insertion_sort(int a[],int n)
{
int i,j,t;
for(i=1;i<=n-1;i++)
{
for(j=i-1;j>=0;j--)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
else
break;
}
}
}
/****************************************************************/
Output->
-------Enter the no of elements in the array 7
Enter the array elements 10 9 6 7 3 2 1

127

The sorted set is:=>

10

128

/****************************************************************/
/* Program for Quick Sort
*/
/* By: Akhilesh Kumar Srivastava
*/
/* Des: This is O(nlogn) Algo in avg case & O(n2) in Worst case */
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
int partition(int*,int,int);
void quicksort(int*,int,int);
/****************************************************************/
void main()
{
int a[50],n,i;
printf("\nEnter the no of elements in the array:=> ");
scanf("%d",&n);
printf("\nEnter the Array elements=> \n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1);
printf("\nSorted set is \n");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
void quicksort(int *A,int low,int high)
{
int j;
if(low<high)
{
j=partition(A,low,high);
quicksort(A,low,j-1);
quicksort(A,j+1,high);
}
}
/****************************************************************/
/* Taking the 1st element as pivot & partitions the array in two halfs*/
/****************************************************************/
int partition(int *A,int low, int up)
{
int i=low; int j=up;int v=A[low]; int t;
do
{
do
{
i++;
}while(A[i]<=v);
while(A[j]>=v)
{
j--;
}
if(i<j)
{
t=A[i];
A[i]=A[j];

129

A[j]=t;
}
}while(i<=j);
if(i>j)
{
t=A[low];
A[low]=A[j];
A[j]=t;
}
return j;
}
/****************************************************************/
Output->
-------Enter the no of elements in the array:=> 6
Enter the Array elements=>
100 50 150 200 30 10
Sorted set is
10
30
50
100
150
Enter the no of elements in the array:=> 8

200

Enter the Array elements=>


35 15 20 25 90 60 55 70
Sorted set is
15
20

35

25

55

60

70

90

130

/****************************************************************/
/* Program for Merge Sort
*/
/* By: Akhilesh Kumar Srivastava
*/
/* Des: This is O(nlogn) Algo in avg case & O(n2) in Worst case */
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void mergesort(int*,int,int);
void merge(int*,int,int,int);
/****************************************************************/
void main()
{
int n,i,a[50];
clrscr();
printf("\nEnter the no of elements in the array:=> ");
scanf("%d",&n);
printf("\nEnter the Array elements=> \n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted set is \n");
for(i=0;i<n;i++)
printf("\t%d",a[i]);
getch();
}
/****************************************************************/
/* Partitioning the array in the arrays of 1 element each & merging
them together to find the single sorted array using divide & conquer
approach */
/****************************************************************/
void mergesort(int*A,int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(A,low,mid);
mergesort(A,mid+1,high);
merge(A,low,mid,high);
}
}
/****************************************************************/
/* Merging the two sorted array to form a single sorted array */
/****************************************************************/
void merge(int *a,int low,int mid,int high)
{
int b[50];
int i=low,j=mid+1,k=low,l;
while(i<=mid&&j<=high)
{
if(a[i]<a[j])
{ b[k]=a[i]; i++; k++; }
else
{ b[k]=a[j]; j++; k++; }
}
while(i<=mid)
{ b[k]=a[i]; i++; k++; }
while(j<=high)
{ b[k]=a[j]; j++; k++; }

131

for(l=low;l<=high;l++)
{
a[l]=b[l];
}
}
/****************************************************************/
Output->
-------Enter the no of elements in the array:=> 6
Enter the Array elements=>
100 50 150 200 30 10
Sorted set is
10
30
50
100
150
Enter the no of elements in the array:=> 8

200

Enter the Array elements=>


35 15 20 25 90 60 55 70
Sorted set is
15
20

35

25

55

60

70

90

132

/****************************************************************/
/* Program for Heap Sort */
/* By: Akhilesh Kumar Srivastava */
/* Description: This is O(nlogn) Algorithm in all three cases */
/****************************************************************/
/* Function Prototyping */
/*****************************/
heapify(int *,int);
adjust(int *,int,int);
heapsort(int *,int);
/*****************************/
void main()
{
int B[20],n,i;
clrscr();
printf("Enter the no of Elements int the array:=>");
scanf("%d",&n);
printf("\nEnter the Array Elements:=>");
for(i=1;i<=n;i++)
scanf("%d",&B[i]);
heapsort(B,n);
printf("Sorted set is:=>\n\n");
for(i=1;i<=n;i++)
printf("\n%d",B[i]);
getch();
}

/****************************************************************/
/* Function Definitions */
/****************************************************************/
heapsort(int *A,int n)
{
int i;
heapify(A,n);
for(i=n;i>=2;i--)
{
swap(&A[i],&A[1]);
adjust(A,1,i-1);
}
}
/*****************************/
heapify(int *A,int n)
{
int i,j;
for(i=n/2;i>=1;i--)
adjust(A,i,n);
}
/*****************************/
adjust(int *A,int i,int n)
{
int j;
while((2*i)<=n)
{
j=2*i;
if((j+1)<=n)
{
if(A[j]<A[j+1])

133

j=j+1;

if(A[i]<A[j])
swap(&A[j],&A[i]);
else
break;
i=j;
}
}
/*****************************/
swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
/*****************************/
Output->
-------Enter the no of elements in the array:=> 6
Enter the Array elements=>
100 50 150 200 30 10
Sorted set is
10
30
50
100
150
Enter the no of elements in the array:=> 8

200

Enter the Array elements=>


35 15 20 25 90 60 55 70
Sorted set is
15
20

35

25

55

60

70

90

134

/****************************************************************/
/* Prog for Radix Sort using Linear Linked list */
/* By: Akhilesh Kumar Srivastava */
/* Des: This is O(n) Algorithm */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
int info;
int radix;
struct node *next;
};
typedef struct node* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void insert(NODEPTR*,int,int);
int delbeg(NODEPTR*);
void traverse(NODEPTR);
/****************************************************************/
void main()
{
NODEPTR list1=NULL,list2=NULL,list3=NULL;
int n,i,x;
NODEPTR p;
printf("\n\nEnter the no. of elements");
scanf("%d",&n);
/*********** Insertion according to the last digit *************/
printf("Enter %d 3-digit numbers",n);
for(i=0;i<n;i++)
{
scanf("%d",&x);
insert(&list1,x,x%10);
}
/******** Insertion according to the second last digit *********/
for(i=0;i<n;i++)
{
x=delbeg(&list1);
insert(&list2,x,(x/10)%10);
}
/********** Insertion according to the First digit *************/
for(i=0;i<n;i++)
{
x=delbeg(&list2);
insert(&list3,x,(x/100)%10);
}
/****** Traversing the list to find the sorted set *************/
printf("\n");
traverse(list3);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/

135

/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/*********************** Ordered Insertion *********************/
/****************************************************************/
void insert(NODEPTR *list,int x,int rad)
{
NODEPTR p=*list,q=NULL,r;
r=getnode();
r->info=x;
r->radix=rad;
r->next=NULL;
if(*list==NULL)
*list=r;
else
{
while(p!=NULL&&rad>=p->radix)
{
q=p;
p=p->next;
}
if(q==NULL)
{
r->next=*list;
*list=r;
}
else
{
r->next=q->next;
q->next=r;
}
}
}
/****************************************************************/
/***************** Traversing the Linked list ******************/
/****************************************************************/
void traverse(NODEPTR p)
{
printf("\nThe Sorted List is\n");
while(p!=NULL)
{
printf("\t%d",p->info);
p=p->next;
}
}
/****************************************************************/
/**** deletion of a node from the beginning of the liked list ***/
/****************************************************************/
int delbeg(NODEPTR *list)

136

NODEPTR p;
int x;
p=*list;
*list=p->next;
x=p->info;
freenode(p);
return x;

}
/****************************************************************/
Output:->
---------Enter the no. of elements5
Enter 5 3-digit numbers123 365 987 563 210
The Sorted List is
123
210

365

563

987

Enter the no. of elements8


Enter 8 3-digit numbers100 359 254 777 698 365 444 420
The Sorted List is
100
254

359

365

420

444

698

777

137

/**************************************************************/
/* Program for Radix Sort by two-dimension arrays */
/* By: Yogesh Sharma */
/* CSE Second Year, Section 'D' */
/* Des: The algorithm achieves the O(n) Complexity */
/**************************************************************/
/***************** Pre-processoer directives ******************/
/**************************************************************/
# include<conio.h>
# include<stdio.h>
# include<math.h>
/**************************************************************/
/********** Global declararion of the array *******************/
int a[100];
/**************************************************************/
/************* Function Definitions ***************************/
/**************************************************************/
int radix(int p,int n )
{
static int num[10][10],b[100];//a copy of a is craeted in b//
int i,j,y,c,l,flag=0;
for(i=0;i<=9;i++)
{
for(j=0;j<=10;j++)
num[i][j]=0;
}
l=pow(10,p);
for(i=0;i<n;i++)
{
b[i]=a[i]/l;
}
while(flag<=n)
{
for(i=0;i<=9;i++)
{
c=0;
for(j=0;j<n;j++)
{
y=b[j]%l;
if(y==i)
{
num[i][c]=a[j];
c++;
flag++;
}

}
}
}
c=0;
for(i=0;i<=9;i++)
{
for(j=0;j<=9;j++)
{
if(num[i][j]!=0)
{
a[c]=num[i][j];
c++;
}
}

138

}
return 0;
}
/**************************************************************/
void main()
{
int i,n,y,p=1;
printf("\n\nEnter the number of elements-");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
y=NULL;
y=a[1];
while(y>0)
{
radix(p,n);
y=y/10;
p++;
}
printf("\n");
for(i=0;i<n;i++)
printf(" %d ",a[i]);
getch();
}
/**************************************************************/
Output->
--------Enter the number of elements-6
123 253 987 222 364 111
111

123

222

253

364

987

Enter the number of elements-5


110 107 365 254 888
107

110

254

365

888

139

/**************************************************************/
/* Program for Shell Sort */
/* By: Yogesh Sharma */
/* Des: The algorithm achieves the O(nlogn) Complexity */
/**************************************************************/
/***************** Pre-processoer directives ******************/
#include <stdio.h>
#include <conio.h>
/**************************************************************/
/********* Function Definitions *******************************/
/**************************************************************/
void shellsort(int x[20],int n,int incrmnts[10],int numinc)
{
int incr,j,k,span,y;
for(incr=0;incr<numinc;incr++)
{
span=incrmnts[incr];
for(j=span;j<n;j++)
{
y=x[j];
for(k=j-span;k>=0&&y<x[k];k-=span)
x[span+k]=x[k];
x[k+span]=y;
}
}
}
/**************************************************************/
void main()
{
int x[20],incrmnts[10],n,numinc,i,c=0;
clrscr();
printf("\nenter the num of elements in array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nenter the %dth element of arrat",i);
scanf("%d",&x[i]);
}
for(j=1;j<n;j++)
incrmnts[c++]=j;
shellsort(x[],n,incrmnts[],c);
for(i=0;i<n;i++)
{
printf("\ the %dth element of array is",i,x[i]);
scanf("%d",&x[i]);
}
getch();
}/**************************************************************/

140

ASSIGNMENT NO. 9
OBJECT:-

PROGRAM BASED ON BINARY TREES.

THEORY AND CONCEPTS :A BINARY SEARCH TREE T IS A BINARY TREE THAT MAY BE EMPTY. A NONEMPTY BINARY SEARCH TREE SATISFIES
THE FOLLOWING PROPERTIES:1-> EVERY ELEMENT HAS A KEY(OR VALUE) AND NO TWO ELEMENTS HAVE THE SAME KEY I.E. ALL KEYS ARE UNIQUE.
2-> THE KEYS, IF ANY, IN THE LEFT SUB TREE OF THE ROOT ARE SMALLER THAN THE KEY IN THE NODE.
3-> THE KEYS, IF ANY, IN THE RIGHT SUB TREE OF THE ROOT ARE LARGER THAN THE KEY IN THE NODE.
4-> THE LEFT AND RIGHT SUB TREES OF THE ROOT ARE ALSO BINARY SEARCH TREES.
REPRESENTATION OF BINARY SEARCH TREE:TYPEDEF STRUCT NODE

{
STRUCT NODE

*LEFT;

INT INFO;
STRUCT NODE *RIGHT;
}BNODE;
BNODE *ROOT;
COMMON OPERATIONS ON BINARY AND BINARY SEARCH TREES:SOME OF THE OPERATIONS THAT ARE COMMONLY PERFORMED ON BINARY AS WELL AS BINARY SEARCH TREES:1-> CREATE AN EMPTY TREE.
2-> TRAVERSE IT.
3-> DETERMINE THE HEIGHT.
4-> DETERMINE THE NUMBER OF ELEMENTS IN IT.
5-> DETERMINE THE NUMBER OF INTERNAL NODES I.E. NON-LEAF NODES.
6-> DETERMINE THE NUMBER OF EXTERNAL NODES I.E. LEAF NODES.
7-> DETERMINE ITS MIRROR IMAGE.
8-> REMOVE IT FROM MEMORY.
THE FOLLOWING ARE SOME OF THE OPERATIONS HAVING RELEVANCE TO ONLY BINARY SEARCH TREES:1-> INSERT A NEW NODE/ELEMENT
2-> SEARCH AN ELEMENT.
3-> FIND THE SMALLEST ELEMENT.
4->FIND THE LARGEST ELEMENT.
5->DELETE A NODE.
6-> FINDING THE LOGICAL SUCCESSOR OF THE GIVEN NODE

141

PRACTICAL/ASSIGNMENTS:(1) WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS OPERATIONS ON A BINARY SEARCH TREE
(MINIMUM, MAXIMUM,LOGICAL SUCCESSOR, TRAVERSAL, DELETION, INSERTION).
(2) WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS TRAVERSAL TECHNIQUES IN A BINARY TREE
RECURSIVELY.
(3) WRITE A MENU DRIVEN PROGRAM TO IMPLEMENTING THE VARIOUS TRAVERSAL TECHNIQUES IN A BINARY TREE NON
RECURSIVELY.
(4) WRITE A PROGRAM FOR IMPLEMENTATION OF HUFFMAN ALGORITHM TO GENERATE THE VARABLE LENGTH CODES.
(5) PROGRAM FOR TRAVERSAL OF THREADED TREES

142

/****************************************************************/
/* Prog for Binary tree traversal */
/* By: Akhilesh Kumar Srivastava */
/* Des: Three Traversals: Preorder,Inorder,Postorder are implemented
recursively */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
char info;
struct node *left;
struct node *right;
};
typedef struct node* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void pretrav(NODEPTR);
void intrav(NODEPTR);
void posttrav(NODEPTR);
NODEPTR maketree(int);
/****************************************************************/
void main()
{
NODEPTR tree=NULL;
clrscr();
tree=maketree('A');
tree->left=maketree('B');
tree->right=maketree('C');
tree->left->left=maketree('D');
tree->right->left=maketree('E');
tree->left->left->left=maketree('F');
printf("\n\nPreorder traversal is:=>");
pretrav(tree);
printf("\n\nInorder traversal is:=>");
intrav(tree);
printf("\n\nPostorder traversal is:=>");
posttrav(tree);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/

143

void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Preorder Traversal of tree ******************/
/****************************************************************/
void pretrav(NODEPTR t)
{
if(t!=NULL)
{
printf("\t%c",t->info);
pretrav(t->left);
pretrav(t->right);
}
}
/****************************************************************/
/***************** Inorder Traversal of tree ******************/
/****************************************************************/
void intrav(NODEPTR t)
{
if(t!=NULL)
{
intrav(t->left);
printf("\t%c",t->info);
intrav(t->right);
}
}
/****************************************************************/
/***************** Preorder Traversal of tree ******************/
/****************************************************************/
void posttrav(NODEPTR t)
{
if(t!=NULL)
{
posttrav(t->left);
posttrav(t->right);
printf("\t%c",t->info);
}
}
/****************************************************************/
/**************** making a node of tree with info x ************/
/****************************************************************/
NODEPTR maketree(int x)
{
NODEPTR p;
p=getnode();
p->info=x;
p->left=NULL;
p->right=NULL;
return p;
}
/****************************************************************/
Output->
-------Preorder traversal is:=>
A
B
D
F
C

Inorder traversal is:=>

Postorder traversal is:=>

144

/****************************************************************/
/* Program for Binary tree creation & traversal recursively */
/* By: Akhilesh Kumar Srivastava */
/* Des: The Insertion process is recursive in nature */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
char info;
struct node *left;
struct node *right;
};
typedef struct node* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void pretrav(NODEPTR);
void intrav(NODEPTR);
void posttrav(NODEPTR);
NODEPTR maketree(int);
create(NODEPTR *t);
/****************************************************************/
void main()
{
NODEPTR tree=NULL;
char c;
clrscr();
printf("Enter the root node");
scanf("%c",&c);
tree=maketree(c);
create(&tree);
printf("\n\nPreorder traversal is:=>");
pretrav(tree);
printf("\n\nInorder traversal is:=>");
intrav(tree);
printf("\n\nPostorder traversal is:=>");
posttrav(tree);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
145

/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Preorder Traversal of tree ******************/
/****************************************************************/
void pretrav(NODEPTR t)
{
if(t!=NULL)
{
printf("\t%c",t->info);
pretrav(t->left);
pretrav(t->right);
}
}
/****************************************************************/
/***************** Inorder Traversal of tree ******************/
/****************************************************************/
void intrav(NODEPTR t)
{
if(t!=NULL)
{
intrav(t->left);
printf("\t%c",t->info);
intrav(t->right);
}
}
/****************************************************************/
/***************** Preorder Traversal of tree ******************/
/****************************************************************/
void posttrav(NODEPTR t)
{
if(t!=NULL)
{
posttrav(t->left);
posttrav(t->right);
printf("\t%c",t->info);
}
}
146

/****************************************************************/
/**************** making a node of tree with info x ************/
/****************************************************************/
NODEPTR maketree(int x)
{
NODEPTR p;
p=getnode();
p->info=x;
p->left=NULL;
p->right=NULL;
return p;
}
/****************************************************************/
create(NODEPTR *t)
{
int x;
char y;
NODEPTR p,q;
printf("Does the left of %c exist?(1/0)",(*t)->info);
scanf("%d",&x);
if(x==1)
{
printf("Enter the info");
fflush(stdin);
scanf("%c",&y);
(*t)->left=maketree(y);
q=(*t)->left;
create(&q);
}
printf("Does the right of %c exist?(1/0)",(*t)->info);
scanf("%d",&x);
if(x==1)
{
printf("Enter the info");
fflush(stdin);
scanf("%c",&y);
(*t)->right=maketree(y);
q=(*t)->right;
create(&q);
}
}

147

OUTPUT
Enter the root nodeA
Does the left of A exist?(1/0)1
Enter the infoB
Does the left of B exist?(1/0)0
Does the right of B exist?(1/0)1
Enter the infoC
Does the left of C exist?(1/0)0
Does the right of C exist?(1/0)1
Enter the infoD
Does the left of D exist?(1/0)0
Does the right of D exist?(1/0)0
Does the right of A exist?(1/0)1
Enter the infoE
Does the left of E exist?(1/0)1
Enter the infoF
Does the left of F exist?(1/0)0
Does the right of F exist?(1/0)0
Does the right of E exist?(1/0)1
Enter the infoG
Does the left of G exist?(1/0)0
Does the right of G exist?(1/0)0
Preorder traversal is:=>
AB

Inorder traversal is:=>

Postorder traversal is:=>

148

/****************************************************************/
/* Prog for Binary Search tree Insertion & Logical successor */
/* By: Akhilesh Kumar Srivastava */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct node
{
char info;
struct node *left;
struct node *right;
struct node *father;
};
typedef struct node* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void intrav(NODEPTR);
NODEPTR maketree(char);
void insertleft(NODEPTR*,char);
void insertright(NODEPTR*,char);
void insert_bst(NODEPTR*,char);
void log_succ(NODEPTR,char);
char min(NODEPTR);
/****************************************************************/
void main()
{
NODEPTR tree=NULL,p,q;
char a[10],ch,x;
int c;
clrscr();
start:
printf("\t1. Insert in the BST\n");
printf("\t2. Inorder Traversal\n");
printf("\t3. Logical Succesor of the node\n");
printf("\t4. exit\n");
printf("===========================\n");
printf("Enter your choice\t");
scanf("%d",&c);
switch(c)
{
case 1:

printf("\nEnter the element to be inserted");


fflush(stdin);
scanf("%c",&x);
insert_bst(&tree,x); break;

case 2:

printf("\nInorder traversal is:=>");


intrav(tree); break;

case 3:

printf("\nEnter the element for logical succesor:=>");


fflush(stdin);
scanf("%c",&x);
log_succ(tree,x); break;

149

exit(1);

default:

printf("\nWrong choice"); break;

case 4:

printf("\nDo you wish to continue? (y/n) ");


fflush(stdin);
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
goto start;
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct node));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Preorder Traversal of tree ******************/
/****************************************************************/
void pretrav(NODEPTR t)
{
if(t!=NULL)
{
printf("\t%c",t->info);
pretrav(t->left);
pretrav(t->right);
}
}
/****************************************************************/
/***************** Inorder Traversal of tree ******************/
/****************************************************************/
void intrav(NODEPTR t)
{
if(t!=NULL)
{
intrav(t->left);
printf("\t%c",t->info);
intrav(t->right);
}
}
/****************************************************************/
/***************** Preorder Traversal of tree ******************/
/****************************************************************/
void posttrav(NODEPTR t)
{
if(t!=NULL)
{
posttrav(t->left);

150

posttrav(t->right);
printf("\t%c",t->info);
}
}
/****************************************************************/
/**************** Making a node of tree with info x ************/
/****************************************************************/
NODEPTR maketree(char x)
{
NODEPTR p;
p=getnode();
p->info=x;
p->left=NULL;
p->right=NULL;
p->father=NULL;
return p;
}
/****************************************************************/
/**********Insertion in binary search tree **********************/
/****************************************************************/
void insert_bst(NODEPTR *tree,char x)
{
NODEPTR p=*tree,q=NULL;
if(p!=NULL)
{
while(p!=NULL)
{
q=p;
if(x<p->info)
p=p->left;
else
p=p->right;
}
if(x<q->info)
insertleft(&q,x);
else
insertright(&q,x);
}
else
(*tree)=maketree(x);
}
/****************************************************************/
/*********** Inserting an element towards left of node m ********/
/****************************************************************/
void insertleft(NODEPTR *m,char x)
{
NODEPTR p;
p=maketree(x);
(*m)->left=p;
p->father=(*m);
}
/****************************************************************/
/*********** Inserting an element towards right of node m *******/
/****************************************************************/
void insertright(NODEPTR *m,char x)
{
NODEPTR p;
p=maketree(x);
(*m)->right=p;
p->father=(*m);

151

}
/****************************************************************/
/*********** Finding the Logical Suceesor of the node x *********/
/****************************************************************/
void log_succ(NODEPTR tree,char x)
{
NODEPTR p,r=tree,q;
while(r!=NULL)
{
if(r->info==x)
break;
if(x<r->info)
r=r->left;
if(x>r->info)
r=r->right;
}
p=r;
if(p->right!=NULL)
{
printf("Logical Successor of %c is\t%c",x,min(p->right));
}
else
{
q=p->father;
while(p==q->right&&q!=NULL)
{
p=q;
q=q->father;
}
if(q!=NULL)
printf("\nLogical Successor of %c is\t%c",x,q->info);
else
printf("\nLogical Successor does not exists");
}

}
/****************************************************************/
/*************** Finding the minimum in the subtree *************/
/****************************************************************/
char min(NODEPTR p)
{
while(p->left!=NULL)
p=p->left;
return(p->info);
}
/****************************************************************/

152

OUTPUT->
-------1. Insert in the BST
2. Inorder Traversal
3. Logical Succesor of the node
4. exit
===========================
Enter your choice
1
Enter the element to be insertedN
Do you wish to continue? (y/n) Y
1. Insert in the BST
2. Inorder Traversal
3. Logical Succesor of the node
4. exit
===========================
Enter your choice
1
Enter the element to be insertedB
Do you wish to continue? (y/n) Y
1. Insert in the BST
2. Inorder Traversal
3. Logical Succesor of the node
4. exit
===========================
Enter your choice
1
Enter the element to be insertedC
Do you wish to continue? (y/n) Y
1. Insert in the BST
2. Inorder Traversal
3. Logical Succesor of the node
4. exit
===========================
Enter your choice
2
Inorder traversal is:=> B
C
Do you wish to continue? (y/n) Y
1. Insert in the BST
2. Inorder Traversal
3. Logical Succesor of the node
4. exit
===========================
Enter your choice
3

Enter the element for logical succesor:=> C


Logical Successor of C is N

153

ASSIGNMENT NO. 10
OBJECT :- PROGRAMS BASED ON GRAPH.
THEORY AND CONCEPTS OF GRAPHS:GRAPH

IS ANOTHER IMPORTANT NON-LINEAR DATA STRUCTURE .

THIS

DATA STRUCTURE IS USED TO REPRESENT

RELATIONSHIP BETWEEN PAIRS OF ELEMENTS WHICH ARE NOT NECESSARILY HIERARCHICAL IN NATURE .

GRAPH IS

DEFINED AS

GRAPH G

IS A ORDERED SET(V,E) WHERE

V(G)
REPRESENTS THE EDGES BETWEEN THESE VERTICES .

REPRESENT THE SET OF ELEMENTS , CALLED VERTICES AND

E(G)

REPRESENTATION OF GRAPHS:- THERE ARE TWO WAYS TO REPRESENT A GRAPH G=(V,E):

AS AN ADJACENCY MATRIX
AS AN ADJACENCY LISTS

OPERATIONS ON GRAPHS:THE FOLLOWING ARE THE OPERATIONS THAT ARE PERFORMED ON THE GRAPH.
CREATING AN EMPTY GRAPH.
ENTERING GRAPH INFORMATION
OUTPUTTING A GRAPH
DELETING A GRAPH
BREADTH FIRST SEARCH
DEPTH FIRST SEARCH
PROBLEMS :(1) WRITE A C PROGRAM FOR DEPTH FIRST SEARCH OF A GRAPH.
(2) WRITE A C PROGRAM FOR BREADTH FIRST SEARCH OF A GRAPH.
(3) WRITE A C PROGRAM FOR WARSHALLS ALGORITHM FOR SHORTEST PATH
(4) WRITE A C PROGRAM FOR WARSHALLS ALGORITHM FOR TRANSITIVE CLOSURE

154

/****************************************************************/
/* Prog for Warshall's Algorithm for shortest path */
/* By: Akhilesh Kumar Srivastava */
/* Des: This is a dynamic programming solution with O(n3) complexity*/
/****************************************************************/
void main()
{
int a[10][10],i,j,n,k,max;
clrscr();
printf("Enter the number of nodes in the graph");
scanf("%d",&n);
printf("Enter the path matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
if(max<a[i][j])
max=a[i][j];
}
}
/******* Setting zero elements to be the maximum element ******/
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(a[i][j]==0)
a[i][j]=2*max+1;
}
}
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(a[i][j]>a[i][k]+a[k][j])
a[i][j]=a[i][k]+a[k][j];
}
}
}
printf("The shortest path matrix is:=>\n");
for(i=1;i<=n;i++)
{
printf("\n");
for(j=1;j<=n;j++)
{
printf("\t%d",a[i][j]);
}
}
getch();
}
/****************************************************************/

155

OUTPUT->
-------Enter the number of nodes in the graph 3
Enter the path matrix
0 100 20
30 0 250
100 300 0
The shortest path matrix is:=>
120
30
100

100
130
200

20
50
120

156

/****************************************************************/
/* Prog for Warshall's Algorithm for transitive Closure */
/* By: Akhilesh Kumar Srivastava */
/****************************************************************/
void main()
{
int a[10][10],i,j,n,k;
clrscr();
printf("enter the number of nodes in the graph");
scanf("%d",&n);
printf("enter the adjacency matrix");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
}
}
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
a[i][j]=a[i][j]|(a[i][k]&a[k][j]);
}
}
}
printf("Adjacency matrix of the Transitive Closure is:=>\n");
for(i=1;i<=n;i++)
{
printf("\n");
for(j=1;j<=n;j++)
{
printf("\t%d",a[i][j]);
}
}
getch();
}
/****************************************************************/

157

/****************************************************************/
/* Prog for Breadth first Search in the GRAPH */
/* By: Akhilesh Kumar Srivastava */
/****************************************************************/
static int BFS[10];
static int rep[10];
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct queue
{
int item[100];
int front;
int rear;
};
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
void init(struct queue *pq);
void insert(struct queue *pq,int x);
int remove(struct queue *pq);
int empty(struct queue *pq);
int repeat();
/****************************************************************/
void main()
{
int a[10][10];
int i,j,n=6,k,x,l;
static int adj[10][10];
struct queue q;
clrscr();
init(&q);
printf("Enter the number of nodes in the graph");
scanf("%d",&n);
printf("Enter the adjacency matrix\n");
for(i=1;i<=n;i++)
{
k=1;
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
if(a[i][j]!=0)
{ adj[i][k]=j; k++; }
}
}
printf("\nThe adjacency list is:=>\n");
for(i=1;i<=n;i++)
{
printf("\n%d:=>\t",i);
k=1;
while(adj[i][k]!=0)
{
printf("\t%d",adj[i][k]);
k++;
}
}
k=1;l=1;
insert(&q,1);
rep[l]=1; l++;

158

do
{
x=remove(&q);
BFS[k]=x;
k++;
i=1;
while(adj[x][i]!=0)
{
if(repeat(adj[x][i])!=1)
{
insert(&q,adj[x][i]);
rep[l]=adj[x][i];
l++;
}
i++;
}
}while(!empty(&q));
printf("\nBFS sequence is:=>\t");
for(i=1;i<=n;i++)
{
printf("\t%d",BFS[i]);
}
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
void init(struct queue *pq)
{
pq->rear=-1;
pq->front=0;
}
/****************************************************************/
void insert(struct queue *pq,int x)
{
if(pq->rear==99)
{
printf("Queue Overflows");
exit(1);
}
pq->rear++;
pq->item[pq->rear]=x;
}
/****************************************************************/
int remove(struct queue *pq)
{
int x;
if(empty(pq))
{
printf("Queue Underflows");
exit(1);
}
x=pq->item[pq->front];
pq->front++;
return x;
}
/****************************************************************/
int empty(struct queue *pq)
{
if(pq->rear-pq->front+1==0)

159

return 1;
else
return 0;

}
/****************************************************************/
int repeat(int x)
{
int i=1;
while(rep[i]!=0)
{
if(rep[i]==x)
return 1;
i++;
}
return 0;
}
/****************************************************************/
Output:->
--------Enter the number of nodes in the graph5
Enter the adjacency matrix
0 1 0 1 0
1 0 1 0 1
0 0 0 1 1
1 1 0 0 1
1 0 0 0 0
The adjacency list is:=>
1:=>
2:=>
3:=>
4:=>
5:=>

2
1
4
1
1

BFS sequence is:=>

4
3
5
2

5
5
1

160

/****************************************************************/
/* Prog for Depth first Search in the GRAPH */
/* By: Akhilesh Kumar Srivastava */
/****************************************************************/
/****************** Pre-processoer directives *******************/
/****************************************************************/
#include<stdio.h>
#define STACKSIZE 100
#define TRUE 1
#define FALSE 0
/****************************************************************/
/***************** Global Decalration of arrays *****************/
/****************************************************************/
static int DFS[10];
static int rep[10];
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct stack
{
char item[STACKSIZE];
int top;
};
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
int repeat();
void init(struct stack*);
void push(struct stack*,int x);
char pop(struct stack*);
int empty(struct stack*);
/****************************************************************/
void main()
{
int a[10][10];
int i,j,n=6,k,x,l;
static int adj[10][10];
struct stack s;
clrscr();
init(&s);
printf("Enter the number of nodes in the graph");
scanf("%d",&n);
printf("Enter the adjacency matrix\n");
for(i=1;i<=n;i++)
{
k=1;
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
if(a[i][j]!=0)
{ adj[i][k]=j; k++; }
}
}
printf("\nThe adjacency list is:=>\n");
for(i=1;i<=n;i++)
{
printf("\n%d:=>\t",i);
k=1;
while(adj[i][k]!=0)
{
printf("\t%d",adj[i][k]);

161

k++;

}
k=1;l=1;
push(&s,1);
rep[l]=1; l++;
do
{
x=pop(&s);
DFS[k]=x;
k++;
i=1;
while(adj[x][i]!=0)
{
if(repeat(adj[x][i])!=1)
{
push(&s,adj[x][i]);
rep[l]=adj[x][i];
l++;
}
i++;
}
}while(!empty(&s));
printf("\nDFS sequence is:=>\t");
for(i=1;i<=n;i++)
{
printf("\t%d",DFS[i]);
}
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/****************************************************************/
/********************* Initialisation of stack ******************/
/****************************************************************/
void init(struct stack *s)
{
s->top=-1;
}
/****************************************************************/
/******************* checking if stack is empty *****************/
/****************************************************************/
int empty(struct stack *s)
{
if(s->top==-1)
return TRUE;
else
return FALSE;
}
/****************************************************************/
/***************** Insertion of an item in stack ****************/
/****************************************************************/
void push(struct stack *s,int x)
{
if(s->top==STACKSIZE-1)
{
printf("stack overflow");
exit(1);
}
s->top++;

162

s->item[s->top]=x;
}
/****************************************************************/
/*************** Removal of an item from stack ******************/
/****************************************************************/
int pop(struct stack *s)
{
int y;
if(empty(s))
{
printf("Stack Underflows");
exit(1);
}
y=s->item[s->top];
s->top--;
return(y);
}
/****************************************************************/
int repeat(int x)
{
int i=1;
while(rep[i]!=0)
{
if(rep[i]==x)
return 1;
i++;
}
return 0;
}
/****************************************************************/
Output:->
--------Enter the number of nodes in the graph5
Enter the adjacency matrix
0 1 0 1 0
1 0 1 0 1
0 0 0 1 1
1 1 0 0 1
1 0 0 0 0
The adjacency list is:=>
1:=>
2:=>
3:=>
4:=>
5:=>

2
1
4
1
1

BFS sequence is:=>

4
3
5
2

5
5
4

163

ASSIGNMENT NO. 12

OBJECT:-

PROGRAM BASED ON SPARSE MATRIX

In the mathematical subfield of numerical analysis a sparse matrix is a matrix populated primarily with
zeros.
Sparsity is a concept, useful in combinatorics and application areas such as network theory, of a low
density of significant data or connections. This concept is amenable to quantitative reasoning. It is also
noticeable in everyday life.
Huge sparse matrices often appear in science or engineering when solving problems for linear models.
When storing and manipulating sparse matrices on the computer, it is often necessary to modify the
standard algorithms and take advantage of the sparse structure of the matrix. Sparse data is by its nature
easily compressed, which can yield enormous savings in memory usage. And more importantly,
manipulating huge sparse matrices with the standard algorithms may be impossible due to their sheer
size. The definition of huge depends on the hardware and the computer programs available to manipulate
the matrix.

Definitions
Given a sparse NM matrix A the row bandwidth for the n-th row is defined as

The bandwidth for the matrix is defined as

Example
A bitmap image having only 2 colors, with one of them dominant (say a file that stores a handwritten
signature) can be encoded as a sparse matrix that contains only row and column numbers for pixels with
the non-dominant color.
64 -16 0 -16 0 0 0 0
-16 64 -16 0 -16 0 0 0
0 -16 64 0 0 -16 0 0
-16 0 0 64 -16 0 -16 0
0 -16 0 -16 64 -16 0 -16
0 0 -16 0 -16 64 0 0
0 0 0 -16 0 0 64 -16
0 0 0 0 -16 0 -16 64
0 0 0 0 0 -16 0 -16

0
0
0
0
0
-16
0
-16
64

164

Storing a sparse matrix


The naive data structure for a matrix is a two dimensional array. Each entry in the array represents an
element ai,j of the matrix and can be accessed by the two indices i and j. For a nm matrix we need at
least (n*m) / 8 bytes to represent the matrix when assuming 1 bit for each entry.
A sparse matrix contains many (often mostly) zero entries. The basic idea when storing sparse matrices
is to only store the non-zero entries as opposed to storing all entries. Depending on the number and
distribution of the non-zero entries, different data structures can be used and yield huge savings in
memory when compared to a naive approach.
One example of such a sparse matrix format is the (old) Yale Sparse Matrix Format [1]. It stores an
initial sparse NN matrix M in row form using three arrays, A, IA, JA. NZ denotes the number of nonzero
entries in matrix M. The array A then is of length NZ and holds all nonzero entries of M. The array IA
stores at IA(i) the position of the first element of row i in the sparse array A. The length of row i is
determined by IA(i+1) - IA(i). Therefore IA needs to be of length N + 1. In array JA, the column index of
the element A(j) is stored. JA is of length NZ.

Another Definition
A good operational definition of sparse matrix is that a matrix is sparse if it contains enough zero
entries to be worth taking advantage of them to reduce both the storage and work required in solving a
linear system. Ideally, we would like to store and operate on only the nonzero entries of the matrix, but
such a policy is not necessarily a clear win in either storage or work. The difficulty is that sparse data
structures include more overhead (to store indices as well as numerical values of nonzero matrix entries)
than the simple arrays used for dense matrices, and arithmetic operations on the data stored in them
usually cannot be performed as rapidly either (due to indirect addressing of operands). There is therefore
a tradeoff in memory requirements between sparse and dense representations and a tradeoff in
performance between the algorithms that use them. For this reason, a practical requirement for a family
of matrices to be `usefully' sparse is that they have only O (n) nonzero entries, i.e. a (small) constant
number of nonzero per row or column, independent of the matrix dimension. For example, most
matrices arising from finite difference or finite element discretizations of PDEs satisfy this condition. In
addition to the number of nonzero, their particular locations, or pattern, in the matrix also has a major
effect on how well sparsity can be exploited. Sparsity arising from physical problems usually exhibits
some systematic pattern that can be exploited effectively, whereas the same number of nonzero located
randomly might offer relatively little advantage.

Diagonal matrix
A very efficient structure for a diagonal matrix is to store just the entries in the main diagonal as a one
dimensional array. For nn matrix we need only n / 8 bytes when assuming 1 bit for each entry.

165

Tri Diagonal matrix


In this matrix, the elements in the main diagonal and the diagonals immediately above this and below
this are non zero and rest elements are zero.
1
1
0
0
0
0
0
0
1
1
1
0
0
0
0
0
0
1
1
1
0
0
0
0
0
0
1
1
1
0
0
0
0
0
0
1
1
1
0
0
0
0
0
0
1
1
1
0
0
0
0
0
0
1
1
1
0
0
0
0
0
0
1
1

Triangular Matrix
1
1
1
1
1
1
1

0
2
2
2
2
2
2

0
0
3
3
3
3
3

0
0
0
4
4
4
4

0
0
0
0
5
5
5

0
0
0
0
0
6
6

0
0
0
0
0
0
7

Representation of Sparse Matrix


1. Vector representaion
Representing the nonzero elements in the single dimension array using the row major order
concept
2. Linked Representaion
Representing the elements in the form of Linear linked list with the fields (Data, row & column
number)

166

/****************************************************************/
/* Prog for addition of two Sparse Matrix */
/* By: Akhilesh Kumar Srivastava */
/* Des: The Sparse matrix is represented by Linked List */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct sparse
{
int info;
int row;
int column;
struct sparse *next;
};
typedef struct sparse* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void freenode(NODEPTR);
void insend(NODEPTR*,int,int,int);
void traverse(NODEPTR);
/****************************************************************/
void main()
{
NODEPTR s1=NULL,s2=NULL,s=NULL,p,q;
int x,c,r,n1,n2,i;
printf("\nEnter the no of nonzero elements in the first Sparse Matrix:=> ");
scanf("%d",&n1);
printf("\nEnter the elements of first sparse matrix (data,row,column):=> ");
for(i=0;i<n1;i++)
{
scanf("%d%d%d",&x,&r,&c);
insend(&s1,x,r,c);
}
printf("\nEnter the no of nonzero elements in the first Sparse Matrix:=> ");
scanf("%d",&n2);
printf("\nEnter the elements of first sparse matrix (data,row,column):=> ");
for(i=0;i<n2;i++)
{
scanf("%d%d%d",&x,&r,&c);
insend(&s2,x,r,c);
}
p=s1; q=s2;
167

while(p!=NULL&&q!=NULL)
{
if(p->row==q->row)
{
if(p->column==q->column)
{
insend(&s,p->info+q->info,p->row,p->column);
p=p->next;
q=q->next;
}
else
{
if(p->column<q->column)
{
insend(&s,p->info,p->row,p->column);
p=p->next;
}
else
{
insend(&s,q->info,q->row,q->column);
q=q->next;
}
}
}
else
{
if(p->row<q->row)
{
insend(&s,p->info,p->row,p->column);
p=p->next;
}
else
{
insend(&s,q->info,q->row,q->column);
q=q->next;
}
}
}
while(p!=NULL)
{
insend(&s,p->info,p->row,p->column);
p=p->next;
}
while(q!=NULL)
{
insend(&s,q->info,q->row,q->column);
q=q->next;
}
printf("The added Sparse Matrix is:=>\n");
168

traverse(s);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
p=(NODEPTR)malloc(sizeof(struct sparse));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Traversing the Linked list ******************/
/****************************************************************/
void traverse(NODEPTR p)
{
while(p!=NULL)
{
printf("\t%d",p->info);
printf(" %d",p->row);
printf(" %d",p->column);
p=p->next;
}
}
/****************************************************************/
/******* Insertion of a node in the end of the liked list *******/
/****************************************************************/
void insend(NODEPTR *list,int x,int r,int c)
{
NODEPTR p=*list,q;
q=getnode();
q->info=x;
q->row=r;
q->column=c;
q->next=NULL;
if(*list==NULL)
*list=q;
else
{
while(p->next!=NULL)
169

p=p->next;
p->next=q;
}
}
/****************************************************************/

Output

170

/****************************************************************/
/* Prog for finding the transpose of the given Sparse Matrix */
/* By: Akhilesh Kumar Srivastava */
/* Des: The Sparse matrix is represented by Linked List */
/****************************************************************/
/****************** Pre-processoer directives *******************/
#include<stdio.h>
/****************************************************************/
/* Structure declararion */
/****************************************************************/
struct sparse
{
int info;
int row;
int column;
struct sparse *next;
};
typedef struct sparse* NODEPTR;
/****************************************************************/
/* Function Prototyping */
/****************************************************************/
NODEPTR getnode(void);
void insend(NODEPTR*,int,int,int);
void insafter(NODEPTR*,int,int,int);
void insbeg(NODEPTR*,int,int,int);
void traverse(NODEPTR);
/****************************************************************/
void main()
{
NODEPTR s1=NULL,s2=NULL,p,q,r;
int x,co,ro,n,i;
clrscr();
printf("\nEnter the no of nonzero elements in the Sparse Matrix:=> ");
scanf("%d",&n);
printf("Enter the elements of first sparse matrix (data,row,column):=> ");
for(i=0;i<n;i++)
{
scanf("%d%d%d",&x,&ro,&co);
insend(&s1,x,ro,co);
}
printf("The Original matrix is:=>");
traverse(s1);
p=s1;
printf("\nThe ordered insertion:=>");
while(p!=NULL)
{
q=s2; r=NULL;
if(q==NULL)
insbeg(&s2,p->info,p->column,p->row);
171

else
{
while(p->column>q->row&&q!=NULL)
{
r=q;
q=q->next;
}
if(q==NULL)
insafter(&r,p->info,p->column,p->row);
else
{
if(p->column<q->row)
{
if(r==NULL)
insbeg(&s2,p->info,p->column,p->row);
else
insafter(&r,p->info,p->column,p->row);
}
else //if(p->column==q->row)
{
while(p->column==q->row&&p->row>q->column&&q!=NULL)
{
r=q;
q=q->next;
}
if(r==NULL)
insbeg(&s2,p->info,p->column,p->row);
else
insafter(&r,p->info,p->column,p->row);
}
}
}
// printf("");
traverse(s2);
p=p->next;
}
printf("\nThe transpose matrix is:=>");
traverse(s2);
getch();
}
/****************************************************************/
/* Function Definitions */
/****************************************************************/
/************** Allocating memory for a new node ****************/
/****************************************************************/
NODEPTR getnode(void)
{
NODEPTR p;
172

p=(NODEPTR)malloc(sizeof(struct sparse));
return p;
}
/****************************************************************/
/***************** freeing the memory not requird ***************/
/****************************************************************/
void freenode(NODEPTR p)
{
free(p);
}
/****************************************************************/
/***************** Traversing the Linked list ******************/
/****************************************************************/
void traverse(NODEPTR p)
{
printf("\n");
while(p!=NULL)
{
printf("\t%d",p->info);
printf(" %d",p->row);
printf(" %d",p->column);
p=p->next;
}
}
/****************************************************************/
/******* Insertion of a node in the end of the liked list *******/
/****************************************************************/
void insend(NODEPTR *list,int x,int r,int c)
{
NODEPTR p=*list,q;
q=getnode();
q->info=x;
q->row=r;
q->column=c;
q->next=NULL;
if(*list==NULL)
*list=q;
else
{
while(p->next!=NULL)
p=p->next;
p->next=q;
}
}
/****************************************************************/
/*Insertion of a node after a node pointed by pointed by pointer p*/
/****************************************************************/
void insafter(NODEPTR *p,int x,int r,int c)
{
NODEPTR q;
173

q=getnode();
q->info=x;
q->row=r;
q->column=c;
q->next=(*p)->next;
(*p)->next=q;
}
/****************************************************************/
/**** Insertion of a node in the beginning of the liked list ****/
/****************************************************************/
void insbeg(NODEPTR *list,int x,int r,int c)
{
NODEPTR p;
p=getnode();
p->info=x;
p->row=r;
p->column=c;
p->next=*list;
*list=p;
}
/****************************************************************/

Output:

174

Vous aimerez peut-être aussi