Data Structure Using C
Data Structure Using C
Computer is an electronic device, which takes the information from user, process it and
gives desired output. In this information is obtained from data, which is known fact.
Information is a processed data, which gives a desired meaning.
Data means known facts, figures or statistics, which is used to manipulation and
calculation purpose. In data there are two types i.e Numeric and Non numeric.
Numeric data means integer and floating point numbers. (Eg:123,-12,12.3, -0.25 etc)
Non-Numeric means characters and Strings (Eg: ‘a’, ‘x’,‘ RAMESH’, ‘SAVTITA’ etc)
While storing these types of data into computer memory, we have to store these data in some
particular order. So we maintain the structure of data, i.e organize the data in a particular
manner.
Definition:
Data structures are implemented by a programming language as data types and operations
they provide.
In this algorithm is technique of solving the problem step by step by carrying out certain task.
And data structure is the way of organizing the data in particular manner.
To develop a program of algorithm we should select an appropriate data structure for that
algorithm. Therefore algorithm and its associated data structures for a program.
1
Data structures using C
Classification of Data structure.
The data structure normally classified as shown in below.
Data Structure
Integer
Linear Non-linear
Floating point
Arrays Tree
Character
Stack Graphs
Double
Queue
Pointer
Linked List
Primitive Data structure :- These are basic data types , which directly manipulated
by the machine instructions. Eg: Integer,floating point numbers, character, string,
pointers etc.
Non-primitive Data structure:- These are derived from primitive data structures,
which can not be manipulated directly by machine instructions. Eg: Arrays, stack,
queues, linked list, files etc.
In non-primitive data structure again there are two types
1. Linear Data structure :- In this only one successor and one predecessor, i.e
it shows the relationship of logical adjacency between the elements. Eg:
Stack, Queue, Array etc.
2. Non-linear Data structure :- In this only one predecessor but more than one
successors. Eg: Trees and Graphs.
2
Data structures using C
Operations on Data structure
The design of an efficient data structure must take operations to be performed on the data
structure for manipulation. Operations on data structure are
Creating : Create means reserving memory for program elements
Inserting : Inserting a data element into data structure..
Deleting : Deleting a data element from data structure.
Selecting : Accessing the data element within a data structure.
Updating : Modify the content of data structure.
Sorting : Arranging the all data elements in a data structure.
Searching: : Finding the particular element from data structure.
Merging : Combining the data element of two different list.
3
Data structures using C
Pointer :- Pointer is one of the most important feature in C language. It is a special data
type which is derived from basic data types(int, float, char, double).
Definition :- Pointer is an variable which holds the address of another variable. It holds only
address i.e pointer values.
Declaration :
Data type * pointer_variable;
Example: int *p; // Here p is an pointer variable of int type.
float *x; // Here x is an variable of float type.
Initialization :
Pointer_variable = & variable_name;
Example: int a=10; // Here a is normal variable
int *p; // Here p is pointer variable
p=&a; // Here p holds address of a
Pointer operators
There are two operators are used in pointers
1) * Indirection operator
2) & Address operator
Indirection operator gives the value of the address.
Address operator gives the address of the variable.
Simple Programs
//Ex 1: Program to add two Integer numbers by using pointer
#include<stdio.h>
void main( )
{
int a,b,c;
int *p,*q;
a=10;
b=20;
p=&a;
q=&b;
c=*p+*q;
printf(“Result = %d”,c);
}
4
Data structures using C
//Ex 2: Program to swap to numbers using pointers
#include<stdio.h>
void main( )
{
int a,b,tmp;
int *p,*q;
a=10;
b=20;
p=&a;
q=&b;
tmp=*p;
*p=*q;
*q=tmp;
printf(“After swapping\n”);
printf(“a= %d and b= %d”,*p,*q);
}
Function declaration means before using calling a function we must declare it. That is
function name, number of argument we are passing, their type and return type.
Eg: int fact(int);
Function call means we are calling the function with function name and passing the
arguments.
Function Definition means actual code to perform into that function.
In calling function, we are passing the parameters. There are two types while passing the
parameters into the function.
1. Call by Value.
2. Call by Reference.
In Call by Value we are passing the values of some variables to the calling function, these
variables are called actual parameters. In function definition we are declaring the
variables, these variables are called formal parameters. The values of actual parameters
are copied into formal parameters. If we made any changes in formal parameters, then
there is no effect on actual parameters.
5
Data structures using C
In Call by Reference we are passing the address of some variables to the calling function,
these variables are called actual parameters. In function definition we are declaring the
variables, these variables are called formal parameters. The addresses of actual
parameters are copied into formal parameters. If we made any changes in formal
parameters, then it effects on actual parameters.
Advantages of Pointers
6
Data structures using C
C language provides the following functions for allocating and deallocating the memory,
1. malloc( )
2, calloc( )
3. realloc( )
4. free ( )
2. calloc():- This function is used to allocate multiple blocks of memory.In this calloc
means contiguous allocation of multiple memory blocks. It is very useful in arrays
and structures.
Syntax :
calloc(n, size);
Ex: ptr=(int *) calloc(5, sizeof(int));
In this calloc function allocates 5 blocks of 2 bytes each.
3. realloc( ):- This function is used to modify the size of already allocated memory
space. Sometimes the allocated memory may not be sufficient and it may require
additional memory space or suppose we want to reduce the size of allocated memory.
For this we are using realloc function.
Syntax :
realloc(ptr,size);
Ex: ptr=(int *) realloc(ptr,3*sizeof(int));
4. free( ):- This function is used to deallocate the memory which is already allocated.
Syntax :
free(ptr);
8
Data structures using C
malloc calloc
1.Allocates single block of memory 1.Allocates multiple blocks of memory
2. Allocated space will not be initialized 2. Each bype of allocated space is
initialized to zero
3.Syntax : malloc(size); 3. Syntax: calloc(n,size);
4. More efficiency 4. Less efficiency
5. Memory is not allocated contiguously 5. Memory is allocated contiguously
9
Data structures using C
Chapter 3: Files
Declaration :
FILE *file_pointer;
Here FILE is a keyword and it is one type of datatype. It should be written in uppercase.
File_pointer:- is an variable which holds the starting address of the file being accessed.
Example:
FILE *infile;
Here infile is file_pointer variable.of type FILE. With the help of file_pointer variable we can
transfer the data from one memory location to another memory location.
Type of files
There are two type in file.
1. Sequential File.
2. Random Access file or Direct File
1. Sequential File:-
In this type of file all records are arranged in particular order. That is records are
stored in consecutive memory location. So we can insert or delete a records sequentially. For
searching record , we start from first to last records until the desired record is found.
Magnetic tape is used to store the records.
10
Data structures using C
Opening a File:
Before performing any operation on file we must open the file with the function fopen( ).
Syntax : File_pointer=fopen(“File Name”, “AccessMode”);
Here File Name is the name of file which is to be opened for any operation.
Access Mode:- It indicates whether file is to be open for reading purpose or writing purpose.
Access Mode Meaning
w File is opened for writing onto the file.But
it overwrites.
r File is opened for reading purpose which is
already existed.
a File is opened for writing purpose which is
appending without overwriting the
previous contents.
w+ Created file is opened for both reading and
writing purpose. But it overwrites.
r+ Already existing file is opened for both
reading and writing purpose.
a+ Already existing file is opened for both
reading and writing purpose without
overwriting.
fscanf( ):- This function is used to read both numeric and non-numeric data from the file.
Syntax:
fscanf (file_pointer, “Control strings”, variable_list );
fgetc( ) :- This function is used to read only singe character from the file.
Syntax :
fgetc(character,file_pointer);
fgets( ) :- This function is used to read only group of characters (string) from the file.
Syntax :
fgets(String , size, file_pointer);
getw( ):- This function is used to read integer values only
11
Data structures using C
Syntax:
n = getw( file_pointer);
Here n is an Integer variable.
Closing a File
The file must be closed after performing the operation. To close a file ‘C’ provides the
function fclose().
Syntax:
fclose (file_pointer );
1. ftell( ):- This function is used to locate the current file position. It takes one
argument as file pointer variable and it returns a number of type long. This value
represents the number of bytes from the beginning of the file to the current position
Syntax : n=ftell(file_pointer)
2. fseek( ):- This function is used locate desired part in a file before data can be read
from or written to. It takes 3 arguments and moves file access position to desired
location within that file.
Syntax : fseek(file_pointer, offset, position);
file_pointer is a pointer of file type,
offset: it indicates number of bytes from specified position in a file.
Position : It indicates the position from which it should start moving
3. rewind( ):- This function is used to reset the position to the beginning of the file. It
moves the file pointer back to the beginning of the file.
Syntax : rewind(file_pointer)
12
Data structures using C
//Example 1: -Write a C program to write and read the content of the file.
#include<stdio.h>
void main( )
{
int rno, ch;
char name[10], clss[10],ele;
FILE *fpt;
while(1)
{
printf("\n1. Write, 2.Read, 3.Quit");
printf("Enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1: fpt=fopen("Std.dat","a");
if(fpt==NULL)
{
printf("File can not open");
exit(0);
}
printf("Enter Roll Number");
scanf("%d",&rno);
printf("Enter name");
scanf("%s",name);
printf("Enter Class");
scanf("%s",clss);
fprintf(fpt ,"%-3d%10s%5s\n",rno,name,clss);
fclose(fpt);
break;
case 2: fpt=fopen("Std.dat","r");
if(fpt==NULL)
{
printf("File can not open");
exit(0);
}
clrscr();
while(!feof(fpt))
{
fscanf(fpt,"%d%s%s\n",&rno,&name,&clss);
printf("%d%10s%s\n",rno,name,clss);
}
fclose(fpt);
break;
case 3 : exit(0);
}
}
13
Data structures using C
}
14
Data structures using C
Chapter 4: Recursion
Definition :
Recursion is the name given to the ability of a function to call itself, until the desired
condition is satisfied.
During each recursive call, the local variables of a recursive function get a different
set of local variables but with the same name.
When we are executing a recursive function, it will not be executed immediately.
First it pushes the all the data onto the stack until desired condition is satisfied. Afterwards it
pops the element from the stack in the reverse order and executed one by one.
Function1( )
Function1( )
Function2( )
Function1( )
Function2( )
Function1( )
15
Data structures using C
#include<stdio.h>
int fact(int);
void main( )
{
int f, n;
printf(“Enter the number”);
scanf(“%d”,&n);
f=fact(n);
printf(“Factorial = %d”, f);
}
int fact(int n)
{
if(n = = 0) return 1;
else
return fact(n-1)*n;
}
#include<stdio.h>
int GCD(int, int);
void main( )
{
int g,m,n;
printf(“Enter the two number”);
scanf(“%d%d” , &m , &n);
g = GCD(m , n);
printf(“GCD = %d”, g);
}
16
Data structures using C
// Example 3: Write a recursive program to find Binomial co-efficient.
#include<stdio.h>
int BC(int, int);
void main( )
{
int n,r, ncr;
printf(“Enter value of n and r”);
scanf(“%d%d” , &n , &r);
ncr = BC(n , r);
printf(“Binomial coefficient = %d”, ncr);
}
#include<stdio.h>
int fibo(int);
void main( )
{
int n, f;
printf(“Enter number”);
scanf(“%d” , &n);
f = fibo( n );
printf(“nth Fibonacci number is = %d”,f);
}
int fibo(int m)
{
if(m= =1) return 0;
else
if (m = = 2) return 1;
else
return fibo(n-1)+fibo(n-2)
}
17
Data structures using C
// Example 5: Write a recursive program to find xn where n>0, n<0 and n=0 .
#include<stdio.h>
float pwr(int,int);
void main( )
{
int x,n;
float power;
printf(“Enter base and exponent”);
scanf(“%d%d” , &x , &n);
power=pwr(x , n);
printf(“Power of x to n is = %f”,power);
}
A C B
Disk-1
Disk-2
Disk-3
Solution :- Now we can solve this problem by using recursion. There are 3 disks so
there are 7 moves in transferring these 3 disks from A to B by taking C as temporary peg.
These moves are as follows .
1. Move Disk1 from A peg to the B peg
2. Move Disk2 from A peg to the C peg.
3. Move Disk1 from B peg to the C peg.
18
Data structures using C
4. Move Disk3 from A peg to the B peg.
5. Move Disk1 from C peg to the A peg.
6. Move Disk2 from C peg to the B peg.
7. Move Disk1 from A peg to the B peg.
A C B A C B A C B
A C B A C B A C B
A C B A C B
19
Data structures using C
/* Moving n-1 disks from C to B peg*/
tower_hanoi(n-1,tmp,dest , src);
}
return;
}
Advantages of Recursion
1. Ease in proving correctness.
2. Ease in complexity analysis
3. Ease to implement and it very efficient.
4. Recursive definition can be easily translated into a recursive function.
5. Recursion avoids the initialization, decisions and other activities like in iterative.
Disadvantages of Recursion
1. Consumes lot of memory
2. It takes more time to compute the result.
3. It executes slowly compare to Iterative.
Applications of Recursion
1. In Symbol manipulation
2. Non-numeric application
3. To solve a problem where there is a recursive in nature.
Iterative Recursion
1. It executes the statements again and 1. It is function which call itself.
again until condition become false.
2. It uses repetition such as for loop, while 2. It uses selection structure such as if or
loop or do-while loop as a control structure switch.
3. It explicitly uses repetition 3. Repetition is done by calling same
function name repeatedly.
4. It terminates when loop structure 4. It terminates when base case is satisfied.
become false.
5. In some situation we are not using 5. It is very efficient use for solving Tower
iterative, for example solving in Tower of of Hanoi and tree traversal problem.
Hanoi and tree traversal problem.
6. It more efficient in terms of memory 6. It is not efficient in term of memory
utilization utilization.
7. Executes much faster. 7. Executes slowly.
20
Data structures using C
Chapter 5 Searching: and Sorting
Searching :
It is one type of problem solving technique where we can find the desired element
from the list.
Definition : To find a particular element from the list
Searching Algorithm
Step 1: Read Key element
Step 2: Search the Key element from the list
Step 3: If the Key element is found in a list then search become “Successful” and returns the
entire record or a pointer to that record
Step 4” Otherwise display “Unsuccessful”
Search and insertion algorithm : An algorithm that is used to insert a new record with the
given key element, when the search is Unsuccessful is called search and insertion algorithm.
Retrieval : It is a successful search operation. It retrieves the desired information from a file
Dictionary: It is a table of records. It is also called search table . A key is used to retrieve the
information from this dictionary.
TYPES OF SEARCHES:
There are two types of searches. This classification depends on whether the search table is
present in the main memory or in the secondary memory. There are
1. Internal searching: In this entire search table is kept in main memory.
2. External searching: In this entire search table is kept in secondary memory.
Search table organization: Search tables that consist of records are organized in several
methods. These are.
1. Sequential organization : Eg: array
2. Non- Sequential organization: Eg: Linked list, tree, graph.
21
Data structures using C
Searching Techniques
1. Linear Search or Sequential Searching.
2. Binary Search
3. Interpolation Search
4. Tree Searching
5. Index Sequential Searching
6. Hashing.
Sequential Searching
This is the simplest technique for searching. In this elements are unordered, so search
scanned from its first record until the desired record is found. That is element are examined
one by one sequential. Hence the name is Sequential or Linear Search. The search table is
organized either as an array or as linked list.
Algorithm:
Sequential_search( a[ ] , n , ele)
// Here a[ ] is an array, n is number of elements, ele is the searching element.
Step1: Flag=0
Step2: for i=0 to n-1 do
Step3: if(a[i] = ele) then
Step4: Flag=1
Step5: Go to step 6
Step6: if (Flag = 1) then
Step7: Display “ Element is Found”
Step8: else
Step9: Display “Element is not Found”
Step10: End
// Program: To search an element from the list using
//Using Iterative method //Using Recursion method
#include<stdio.h> #include<stdio.h>
void main( ) int linsearch(int a[],int n, int key);
{ void main( )
int a[10] , i .n,x, flag=0; {
printf(“Enter the number of elements”); int a[10] , i .n,x, flag ;
scanf(“%d”, &n); printf(“Enter the number of elements”);
printf(“Enter the elements”); scanf(“%d”, &n);
for(i=0 ; i<n ; i++) printf(“Enter the elements”);
scanf(“%d”, &a[i]); for(i=0 ; i<n ; i++)
printf(“Enter the search elements”); scanf(“%d”, &a[i]);
scanf(“%d”, &x); printf(“Enter the search elements”);
for(i=0 ; i<n ; i++) scanf(“%d”, &x);
{ flag = linsearch(a , n , x);
if(a[i]= = x) if(flag= = 1)
{ printf(“Element is found”);
flag=1; else
break; printf(“Element is not found”);
} }
} int linsearch(int a[],int n ,int key)
if(flag= = 1) {
printf(“Element is found”); if( n < 0 ) return 0;
else if( a[n-1]= = key) return 1;
printf(“Element is not found”); 22 else
} return linsearch(a,n-1,key);
}
Data structures using C
Binary Searching
In linear search it takes lengthy time for searching the element if the list is large. For
avoiding that we are using Binary Search. It is a divide and conquers strategy. In this we
divide the list into two part and find out the middle element, if the middle element is
searching element, then search become successful, otherwise to check whether the search
element is belongs to upper part of the list or lower part of the list. And again the divide the
list into two part, until element is found.
Algoritm:
Step1: Start
Step2: Read the number of elements, N
Step3: Read the elements.
Step4: for i=0 to n-1
Step5: Read a[i];
Step6: Read the search element, S
Step7: Initially flag=0, low =0 , high= n-1
Step8: while (low <= high)
Step9: mid = (low + high)/2;
Step10: if(a[mid] = S) then
Step11: flag=1 goto step
Step12: else
Step13:if ( a[mid] < S) then
Step14: low = mid + 1;
Step15: else
Step16: high = mid -1
Step17: while end
Step18:if ( flag = 1) then
Step19: Diplay “Element is Found”
Step20: else
Step21: Display “Element is not Found”
Step22: Stop
23
Data structures using C
24
Data structures using C
25
Data structures using C
Sorting
Sorting it is a one type of problem solving technique. Suppose we want to
search for the telephone number of a person in the telephone directory. If the
telephone directory is not sorted in alphabetical order, then we may have to search for
the entire telephone directory. Since telephone directory is sorted, so we can find any
telephone number easily.
The main goal of sorting is to generate report of data and accessing data
efficiency.
General Background:
Consider a file is collection of related records. Each record is having their unique key. Which
maintains the record uniquely. Here key is used to sort the records in a specified order. In
general a file is said to be sorted if the key associated with it record precedes the key.
Consider student information file system in which all the names are sorted in alphabetical
order. Here name is the key used to sorted the student record.
There are two type of sorting.
1. Internal Sorting: If all the records to be sorted are present in the main memory then
such a sorting is called internal sorting.
2. External Sorting.: If some of the records to be sorted are kept on secondary
memory. It is called external sorting.
Efficiency of sorting
There are various types are available for sorting technique. But they have their own
advantages and disadvantages. Different techniques are useful in different application.
There are three most important consideration one should look at during the selection of a
sorting technique. They are.
1. Coding time: - The amount of time invested in writing full length sorting program.
2. Execution time: - The time required executing the program.
3. Space (Memory):- The amount of memory space to store the program.
26
Data structures using C
1. Selection Sort.
This is one type of sorting technique. In this we are selecting the smallest elements and put it
into the first place, select the second smallest element and put into the second place, and so
on. It takes n-1 passes to sort the elements.
45 34 34 23 12 12 12 12 12
34 45 45 45 45 45 45 34 23
56 56 56 56 56 56 56 56 56
23 23 23 34 34 34 34 45 45
12 12 12 12 23 23 23 23 34
Pass-1 Pass-2
12 12 12 12 12
23 23 23 23 23
56 45 34 34 34
45 56 56 56 45
34 34 45 45 56
Pass-3 Pass-4
#include<stdio.h>
void main( )
{
int a[10] , i .n,tmp;
printf(“Enter the number of elements”);
scanf(“%d”, &n);
printf(“Enter the elements”);
for(i=0 ; i<n ; i++)
scanf(“%d”, &a[i]);
for(i=0 ; i<n-1 ; i++)
{
for(j=i+1 ; j<n; j++)
{
if( a[i] < a[j] )
{
tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
}
}
printf(“\n Array elements are \n”);
for(i=0; i<n; i++)
printf(“%d\n”, a[i]); }
27
Data structures using C
2. Bubble Sort.
This is simplest and easiest type of sorting technique. In this method during each pass each
element of an array is compared with its successor. If the element is not in the proper order
then they are interchanged. At the end of the first pass the largest element will be bubbled up
to the last position. And similarly at the end of second pass the second largest is bubbled up
to the last but one position and so on.
45 34 34 34 34 34 34 34 34
34 45 45 45 45 45 45 23 23
56 56 56 23 23 23 23 45 12
23 23 23 56 12 12 12 12 45
12 12 12 12 56 56 56 56 56
Pass-1 Pass-2
34 23 23 23 12
23 34 12 12 23
12 12 34 34 34
45 45 45 45 45
56 56 56 56 56
Pass-3 Pass-4
#include<stdio.h>
void main( )
{
int a[10] , i .n, tmp;
printf(“Enter the number of elements”);
scanf(“%d”, &n);
printf(“Enter the elements”);
for(i=0 ; i<n ; i++)
scanf(“%d”, &a[i]);
for(i=0 ; i<n ; i++)
{
for(j=i+1 ; j< (n-i-1); j++)
{
if( a[j] < a[j+1] )
{
tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
}
}
}
printf(“\n Array elements are \n”);
for(i=0; i<n; i++) printf(“%d\n”,a[i]); }
28
Data structures using C
3. Merge Sort.
This is one type divide and conquers sorting technique. In this method we divide the list into
smaller and smaller part until individual element. Compare these individual element and sort
into single list that is merging the element until n-1 elements. This process is called merge
sort.
93 77 65 49 85 51 41 28 18 43 27 21
93 77 65 49 85 51 41 28 18 43 27 21
93 77 65 49 85 51 41 28 18 43 27 21
93 77 65 49 85 51 41 28 18 43 27 21
93 77 65 49 85 51 41 28 18 43 27 21
77 93 65 49 85 51 28 41 18 27 43 21
65 77 93 49 51 85 18 28 41 21 27 43
49 51 65 77 85 93 18 21 27 28 41 43
18 21 27 28 41 43 49 51 65 77 85 93
C Funtion
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);
}
}
void merge(int a[],int low,int mid,int high)
{
int i,j,k,c[10];
i=low;
29
Data structures using C
j=mid+1;
k=0;
while(i<=mid && j<=high)
{
if(a[i]<=a[j])
{
c[k]=a[i];
i++;
k++;
}
else
{
c[k]=a[j];
j++;
k++;
}
}
while(i<=mid)
{
c[k]=a[i];
i++;
k++;
}
while(j<=high)
{
c[k]=a[j];
j++;
k++;
}
for(i=0;i<k;i++)
a[i]=c[i];
}
#inclue<stdio.h>
void megre(int a[], int, int , int);
void mergesort(int a[], int, int);
void main( )
{
int a[10],n,i;
printf(“Enter the number of elements”);
scanf(“%d”,&n);
printf(“Enter the elements “);
for( i = 0 ; i < n ; i ++)
scanf(“%d”,&a[i]);
mergesort(a, 0, n-1);
printf(“\n Sorted elements are\n”);
30
Data structures using C
for( i = 0 ; i < n ; i ++)
printf(“\n%d”,a[ i ]);
}
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);
}
}
void merge(int a[ ],int low,int mid,int high)
{
int i,j,k,c[10];
i=low;
j=mid+1;
k=0;
while(i<=mid && j<=high)
{
if(a[i]<=a[j])
{
c[k]=a[i];
i++;
k++;
}
else
{
c[k]=a[j];
j++;
k++;
}
}
while(i<=mid)
{
c[k]=a[i];
i++;
k++;
}
while(j<=high)
{
c[k]=a[j];
j++;
k++;
}
for(i = 0 ; i < k ; i ++)
a[i]=c[i];
31
Data structures using C
}
4. Quick Sort.
This is also one type of divide and conquers sorting technique. In this method we are
partitioning the list and one of the array elements is chose as a key value. This key value can
be the first element of an array. That is, if A is an array then key =A [0] and rest of the array
elements are grouped into two partitions such that
One partition contains elements smaller than the key value.
Another partition contains elements larger than the key value.
Partition 1 Partition 2
#include<stdio.h>
void quicksort ( int a[ ] , int low , int high);
int partition ( int a[ ] , int low , int high );
void main( )
{
int a[10] , i .n,tmp;
printf(“Enter the number of elements”);
scanf(“%d”, &n);
printf(“Enter the elements”);
for(i=0 ; i<n ; i++)
scanf(“%d”, &a[i]);
quicksort ( a ,0 , n-1 );
printf(“\n Array elements are \n”);
for(i=0; i<n; i++)
printf(“%d\n”,a[i]);
}
5. Insertion Sort.
This sorting technique involves the insertion of an elements into a sorted array in such a way
that the resulting array is also sorted. In this sort we assume that the first element of an array
is in its proper position. Then we take next element from the unordered array and place it in
its proper position, by comparing it with the one already sorted. This process is continued
until all the elements are placed into their proper positions.
#include<stdio.h>
void main( )
{
int a[10],i,j,n,tmp;
clrscr( );
printf("Enter the elements");
scanf("%d", &n);
printf("Enter the elements");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
j = i;
while(j > = 1)
33
Data structures using C
{
if(a[j] < a[j-1])
{
tmp=a[j];
a[j]=a[j-1];
a[j-1]=tmp;
}
j--;
}
}
printf("\n Sorted elements are\n");
for(i=0;i<n;i++)
printf("%d\n", a[i]);
getch( );
}
Chapter 6 : Stack
Example : Suppose n number of books are placed one above the other. The books are
inserted from top only. If a book is required, then the top book is selected. This process of
inserting the books at the top and removing the books from the top is called stacking of
books.
Representation of Stacks
We can represent the stacks in the computer memory by using either the static representation
or the dynamic representation. The static representation means array representation. The
dynamic representation means the linked list representation.
Operations on Stack:
There are three important operations on stack, these are
1. Push
2. Pop
3. Display.
1. Push operation
This operation adds (pushes) a new element on to the stack. While inserting a new element
into the stack, we first check out whether stack is full or not. If it is full then it is not possible
to insert into the stack. That is to check whether it exceeds maxsize or not.
If stack is not full then only we can insert the new element into the stack.
Top
Top 50 50
Top 40 40 40
30 30 30 30
Top
Top 20 20 20 20 20
Top 10 10 10 10 10 10
Over Flow: IF the stack is full it is not possible to insert a new element onto the
stack.. This is called Stack is Over Flow.
2. Pop operation
This operation deletes (pops) an element from the top of the stack. While deleting an
element from the stack, we first check out whether stack is empty or not. If it is empty then it
is not possible to delete from the stack. That is to check whether it top is less than zero or
not. If stack is not empty then only we can delete the element from the stack.
Top 50
40 Top 40
30 30 Top 30
20 20 20 Top 20
10 10 10 10 Top 10
) Top
Delete
Stack Empty
Under Flow: IF the stack is empty it is not possible to delete an element from the
stack.. This is called Stack is Under Flow.
36
Data structures using C
3. Display operation
We can access the stack element from top of the stack until it reaches 0 that is bottom of the
stack. If the stack is empty, then it display the message “Stack is Empty” otherwise it
displays the all elements from the stack
void display( )
{
int i;
if(top= = -1)
printf(“Stack is Empty”);
else
for ( i = top ; i > = 0; i - - )
printf( “%d\n”, stack[i]);
}
void push(int x)
{
if(top==MAX-1)
{
printf("Stack is Over Flow");
return;
}
top=top+1;
stack[top]=x;
}
int pop( )
{
if(top==-1)
{
printf("Stack is Under Flow");
return 0;
}
return(stack[top--]);
}
void display( )
38
Data structures using C
{
int i;
if(top==-1)
printf("Stack is Empty");
else
for(i = top; i>=0 ; i--)
printf("%d\n", stack[i]);
}
Example :
Infix Expression Prefix Expression
1. A+B +AB
2. A–B –AB
3. A*B *AB
4. A/B /AB
5. A+B *C +A*BC
6. A+B– C –+ABC
7. (A + B) * C * + A BC
8. X/Y^Z+A +/X^YZA
9. A*B+C/D +*AB/CD
10. B * C – D + E / F / (G + H) +–*BCD//EF+GH
3. Postfix:
In this type expression operator is after its two operands. This is also called suffix
notation. It is a reverse polish notation
Example :
Infix Expression Postfix Expression
1. A+B AB+
2. A–B AB–
3. A*B AB*
4. A/B AB/
5. A+B *C ABC*+
6. A+B– C AB+C–
7. (A + B) * C AB+C*
39
Data structures using C
8. X/Y^Z+A XYZ^/A+
9. A*B+C/D AB*/CD+
10. B * C – D + E / F / (G + H) BC*DEF/GH+/–+
40
Data structures using C
Conversion of an arithmetic expression from infix to postfix.
In converting an expression from infix to postfix the following assumptions are made.
1. Only single character operands are used.
2. Only + – * and / operators are considered
3. Expression is error free.
The conversion procedure assigns a precedence to each operator. This helps in determining
where an operator will be placed in the postfix expression.
Algorithm:
Step 1:- Scan the infix expression from LEFT to RIGHT
Step 2:- If the scanned symbol is left parenthesis push it onto the stack
Step 3:- If the scanned symbol is an operand then place directly in the postfix expression.
Step 4:- If the scanned symbol is right parentheses, then go on popping all the elements from
the stack and place them in the postfix expression till we get matching left
parenthesis.
Step 5:- If the scanned symbol is an operator then go on removing all the operators from the
stack and place them in the postfix expression . If and only if the precedence of the
operator which is on the top of the stack is greater than or equal to the precedence of
the scanned operator. Otherwise push the scanned operator onto the stack.
41
Data structures using C
#include<stdio.h>
#include<string.h>
int i=0, pos=0, top=-1,len;
char symbol, tmp;
char infix[20], postfix[20], stack[20];
void push(char);
char pop( );
void infix_postfix(char a[], char b[]);
void main( )
{
clrscr( );
printf("Enter the infix expression");
scanf("%s", infix);
infix_postfix(infix,postfix);
printf(" Postfix expression = %s", postfix);
getch( );
}
42
Data structures using C
push(symbol);
break;
default: postfix[pos++]=symbol;
break;
}
i++;
}
while(top > 0)
{
tmp=pop();
postfix[pos++]=tmp;
}
return;
}
void push(char ele)
{
top=top+1;
stack[top]=ele;
}
char pop()
{
char ele;
ele=stack[top];
top=top-1;
return (ele);
}
int precd(char ele)
{
int p;
switch(ele)
{
case '^': p=3; break;
case '*':
case '/': p=2; break;
case '+':
case '-': p=1; break;
case ')':
case '(': p=0; break;
case '#': p=-1; break;
}
return p;
}
43
Data structures using C
Evaluation of a Postfix Expression.
It is another application of stack. In this we are evaluate the postfix expression. In this we are
storing the numeric value instead of character into the stack.
Algorithm
Step 1: Store the numeric values corresponding to each operand in an array.
Step 2: Scan the given postfix expression from LEFT to RIGHT
Step 3: If the scanned symbol is an operand , then push its value onto the stack.
Step 4: If the scanned symbol is an operator then pop out two values from the stack and
assign them respectively to operand2 and operand1.
Step 5: Then perform the required arithmetic operation.
If operator is * then result =operand1 * operand2
If operator is / then result =operand1 / operand2
If operator is + then result =operand1 + operand2
If operator is - then result =operand1 - operand2
Step 6: Push the result onto the stack
Step 7: Repeat step 1 to 4 until all the symbols in the postfix expression are over.
44
Data structures using C
// Program to evaluate postfix expression
#include<stdio.h>
#include<math.h>
#include<ctype.h>
#include<string.h>
float stack[10];
int top=-1;
void push(float);
float pop( );
float eval_exp(char *n,float a[]);
void main( )
{
int i=0;
char postfix[20];
float value[20],result;
printf("Enter the valid Postfix Expression");
scanf("%s",postfix);
while(postfix[i]!='\0')
{
if(isalpha(postfix[i]))
{
printf("Enter the value of %c", postfix[i]);
scanf("%f", &value[i]);
}
i++;
}
result=eval_exp(postfix, value);
printf("The result of %s = %f", postfix , result);
getch();
}
float eval_exp(char postfix[],float value[])
{
int i=0;
float op1,op2,result;
char ch;
while(postfix[i]!='\0')
{
ch=postfix[i];
if(isalpha(postfix[i]))
push(value[i]);
else
{
op2=pop( );
op1=pop( );
switch(ch)
{
case '+': push(op1+op2); break;
case '-': push(op1-op2); break;
case '*': push(op1*op2); break;
45
Data structures using C
case '/': push(op1/op2); break;
case '^': push(pow(op1,op2)); break;
}
}
i++;
}
result=pop();
return (result);
}
void push(float num)
{
top++;
stack[top]=num;
}
float pop( )
{
float n;
n=stack[top];
top--;
return n;
}
46
Data structures using C
Chapter 7 : Queue
Front 10 20 30 40 50 Rear
Queue
In the above queue, there are five elements . This number is the capacity or the size of a
queue. This queue cannot hold more than five elements. And the element 50 is the most
recently added one and hence it is the last to be deleted.
Representation of a Queue.
We can represent the queue in the computer memory by using either the static representation
or the dynamic representation. The static representation means array representation. The
dynamic representation means the linked list representation.
Operations on a queue:
There are three important operations on queue, these are
1. Insert operation : It inserts a new data item at the rear of the queue.
2. Deletion operation: It deletes and then returns the data item at the front of the queue
3. Display operation : It displays the contents of queue.
Types of queue
1. Simple Queue / Ordinary Queue.
2. Circular Queue
47
Data structures using C
3. Double ended Queue
4. Priority Queue.
1. Simple Queue:
F R
Now Insert Element 10 to the queue.
Rear= Rear + 1
10
Front = 0
F R
F R
Now Insert 30 to the queue.
Rear= Rear + 1
10 20 30
Front = 0
48
Data structures using C
F R
F R
Now delete an element
20 30 40 Front = Front +1
F R
Now delete an element
30 40
Front = Front +1
F R
49
Data structures using C
// Program to Demonstrate the Queue operation, such as insertion deletion and display
#include<stdio.h>
#define MAX 5
void QInsert( );
void QDelete( );
void QDisplay( );
int q[MAX], front = -1, rea r= -1, ch;
void main( )
{
clrscr( );
while(1)
{
printf("\n-------------\n");
printf("1.Insert \n 2.Delete \n 3.Display \n 4.Exit \n");
printf("\n------------------\n");
printf("Enter your choice");
scanf("%d", &ch);
switch(ch)
{
case 1: QInsert( ); break;
case 2: QDelete( ); break;
case 3: QDisplay( ); break;
case 4: exit(0);
}
}
}
void Qinsert( )
{
int n;
if(rear = = MAX-1)
{
printf("\n Queue is Full\n");
return;
}
else
{
printf("Enter the element");
scanf("%d", &n);
rear++;
q[rear]=n;
if(front = = -1) front++;
}
return;
}
50
Data structures using C
void QDelete( )
{
int n;
if(front == -1)
{
printf("\n Queue is Empty \n");
return;
}
else
{
if(front = =rear)
front = rear = -1;
else
{
n=q[front];
printf("\n Deleted element is = %d", n);
front ++;
}
}
}
void QDisplay ( )
{
int i;
if(front = = -1)
printf("\n Queue is Empty\n");
else
{
printf("\n Queue Elements are \n");
for(i=front; i < = rear; i++)
printf("%3d", q[i]);
}
}
2. Circular queue:
In simple queue, if we delete all the elements from the queue. At the end of these deletions
the value of Front would become n value. In this situation , if we attempt to insert a new data
item to the queue., we would receive a message “ Queue is Full”, even though queue is not
full. This problem can be overcome by implementing a queue as a circular queue.
In circular queue, if we reach the end while inserting elements to it, it is possible to
insert new elements if the slots at the beginning of the circular queue are empty.
Q [Max-1] Q [0]
Rear Front 51
Q [1]
Data structures using C
Here also Front and Rear are used to keep track of the
elements to be deleted and inserted respectively.
Front is one position behind the first element of the
queue. Front = Rear if and only if the queue is empty.
Each time a new element is inserted into the queue the
variable Rear is incremented by one. Similarly each
time an item is deleted from the queue; the variable
front is increment by one. In this we maintain the one
counter variable. It increments when the inserting a new
element and decrement when we are deleting the
element.
52
Data structures using C
// Program to Demonstrate the Circular Queue operation, such as insertion deletion and
display
#include<stdio.h>
#define MAX 5
void CQInsert( );
void CQDelete( );
void CQDisplay( );
int q[MAX], front = -1, rea r= -1, ch,count=0,ele;
void main( )
{
clrscr( );
while(1)
{
printf("\n-------------\n");
printf("1.Insert \n 2.Delete \n 3.Display \n 4.Exit \n");
printf("\n------------------\n");
printf("Enter your choice");
scanf("%d", &ch);
switch(ch)
{
case 1: CQInsert( ); break;
case 2: CQDelete( ); break;
case 3: CQDisplay( ); break;
case 4: exit(0);
}
}
}
void CQinsert( )
{
if(count = maxsize-1)
{
printf(“Circular Queue is Full ”);
return;
}
printf(“Enter the element”);
scanf(“%d”,&ele);
Rear = (Rear +1) % MAX;
53
Data structures using C
count++;
queue[Rear]=ele;
}
int CQdelete( )
{
if( count = = 0)
{
printf (“Circular Queue is Empty”);
return;
}
ele= queue[Front] ;
count - -;
Front = (Front + 1) % Max;
return ele;
}
void CQDisplay ( )
{
int i;
if(count = = 0)
printf("\n Circular Queue is Empty\n");
else
{
printf("\n Circular Queue Elements are \n");
for(i=1; i < = count; i++)
{
printf("%3d", q[Front]);
Front=(Front+1)%Max;
}
}
54
Data structures using C
4. Priority Queue.
A priority queue a queue in which items can be inserted or deleted based in the priority. An
element with highest priority is processed before processing any of the lower priority
elements. If the elements in the queue are of same priority , then the elements ,which is
inserted first into the queue, is processed.
In priority queue, there are two types.
a) Ascending priority queue: In this elements can be inserted in any order. But while
deleting an element from the queue, only the smallest element is removed first.
b) Descending priority queue: In this elements can be inserted in any order. But while
deleting an element from the queue, only the largest element is removed first.
55
Data structures using C
Application of queue.
Start
10 20 30 40
Null
Null Pointer: The link field of the last node contains zero rather than a valid address. It is a
null pointer and indicates the end of the list.
External Pointer: It is the pointer to the vary first node in the linked list. It enables us to
access the entire lined list. In the above figure start is an external pointer.
Empty List: IF the nodes are not present in a linked list, then it is called an empty linked
list or simply empty list or null list.
56
Data structures using C
Physical view:
Data Link
node
Logical view: struct node
{
int data;
struct node *link;
};
Self-referential structures :- The node has clearly two fields. The first one is an integer
data item and second one is link( pointer) to the next node of the same type. Hence such
structures are called self-referential structures.
57
Data structures using C
Basically, we can put linked lists into the following four types.
1. Singly-linked list
2. Doubly linked list
3. Circular linked list
4. Circular doubly linked list
Basic Operations
The basic operations to be performed on the lists are as following.
1.Creation. : It is used to create a new linked list. Here, the constituent node is created
2.Insertion. : It is used to insert a new node in the linked list at the specified position.
3.Deletion. : It is used to delete an item from the linked list.
4. Traversing.: It is used to traverse the all nodes of a linked list from one end to another
end. In this 2 types.
a. Forward Traversing : Start traversing from first node to last node.
b. Backward Traversing : Start traversing from last node to first node.
5.Searching : It is used to access the desired node in the linked list.
6.Concatenation : It is used to join the two lists.
7.Display : It is used to display the node information from the linked list.
A singly linked list is a dynamic data structure . It may be grow or shrink depending upon
the operation made. It is one in which all nodes are linked together in some sequential
manner. Hence, it is also called linear linked list. Clearly it has the beginning and the end.
In C a linked list is created using structures, pointers and dynamic memory allocation
function malloc. In this we consider head is an external pointer. It is used to create and
access the nodes from linked list.
Creating a node:
struct node
{
int data;
struct node *next;
};
typedef struct node *Node;
Node * head;
Inserting Nodes:
In this we are inserting a new element into the linked list it has the following three instances.
1. Inserting at the beginning of the list.
2. Inserting at the end of the list.
3. Inserting at the specified position within the list.
To insert the element into the linked list, the following three things should be done.
1. Allocating a node
58
Data structures using C
2. Assigning the node.
3. Adjusting the position.
head
10 20 30 40
Null
50
temp
Node getnode()
{
Node tmp;
tmp=(Node)malloc(sizeof(struct node));
tmpnext=NULL;
return tmp;
}
59
Data structures using C
tmpdata=ele;
if(head= =NULL)
head=tmp;
else
{
tmpnext=head;
head=tmp;
}
return head;
}
head
10 20 30 40
50
Null
temp
Node getnode()
{
Node tmp;
tmp=(Node)malloc(sizeof(struct node));
tmpnext=NULL;
return tmp;
}
Node insertEnd(int ele)
{
Node tmp , p;
tmp=getnode( );
60
Data structures using C
tmpdata=ele;
if(head= =NULL)
head=tmp;
else
{
p=head;
while(pnext!=NULL)
p=pnext;
pnext=tmp;
}
return head;
}
10 20 30 40
50
temp
Node getnode( )
{
Node tmp;
tmp=(Node)malloc(sizeof(struct node));
tmpnext=NULL;
return tmp;
}
Node insertS(int ele,int k)
{
int count=0;
Node tmp,p;
61
Data structures using C
tmp=getnode( );
tmpdata=ele;
if(head= =NULL)
head=tmp;
else
{
p=head;
while(pvnext!=NULL || count<k)
{
p=pnext;
count++;
}
if(p= =NULL)
{
printf("Not a Valide position");
return head;
}
tmpnext=pnext;
pnext=tmp;
}
return head;
}
Deleting Nodes:
In this we are deleting a node from the linked list it has the following three instances.
1. Deleting the first node of the linked list.
2. Deleting the last node of the linked list.
3. Deleting the specified node within the linked list.
head temp
10 20 30 40
Null
62
Data structures using C
{
int data;
struct node *next;
};
typedef struct node *Node;
Node deleteF()
{
Node tmp=head;
if(head= =NULL)
{
printf("List is Empty\n");
return head;
}
head=headnext;
free(tmp);
return head;
}
head p temp
10 20 30 40
Null
Node deleteE()
{
Node tmp=head,p;
if(head= =NULL)
{
63
Data structures using C
printf("List is Empty\n");
return head;
}
while(tmpnext!=NULL)
{
p=tmp;
tmp=tmpnext;
}
free(tmp);
pnext=NULL;
return head;
}
10 20 30 40 50
Node deleteS(int k)
{
int count=1;
Node tmp=head,p=tmp;
if(head= =NULL)
{
printf("List is Empty\n");
return head;
}
while(tmpnext!=NULL)
{
if(k==count)
{
pnext=tmpnext;
64
Data structures using C
free(tmp);
}
p=tmp;
tmp=tmpnext;
count++;
}
if(tmp= =NULL)
{
printf("Invalid Position\n");
return head;
}
return head;
}
// Program to demonstrate the linked list operations- Insert node from Beginning, End,
Specified position, Deleting Node from Beginning, End, Specified Position and Display the
elements.
#include<stdio.h>
struct node
{
int data;
struct node *next;
};
typedef struct node *Node;
Node getnode();
Node insert(int);
Node insertE(int);
Node insertS(int,int);
Node deleteF();
Node deleteE();
Node deleteS(int);
void display(Node);
Node head=NULL;
void main()
{
int ch,ele,p;
clrscr();
while(1)
{
printf("\n----Insert Node -----\n");
printf("1.Front \n2.End \n3.Specific position \n");
printf("\n----Delete Node -----\n");
printf("4.Front \n5.End \n6.Specific position \n7.Display\n8.Exit\n");
printf("Enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the element");
65
Data structures using C
scanf("%d",&ele);
head=insert(ele);
break;
case 2: printf("Enter the element");
scanf("%d",&ele);
head=insertE(ele);
break;
case 3: printf("Enter the element");
scanf("%d",&ele);
printf("Enter the position");
scanf("%d",&p);
head=insertS(ele,p);
break;
case 4: head=deleteF();
break;
case 5: head=deleteE();
break;
case 6: printf("Enter the position");
scanf("%d",&p);
head=deleteS(p);
break;
case 7: printf("Elements of list are\n");
display(head);
break;
case 8: exit(0);
}
}
}
Node getnode()
{
Node tmp;
tmp=(Node)malloc(sizeof(struct node));
tmpnext=NULL;
return tmp;
}
66
Data structures using C
return head;
}
Node deleteF()
{
67
Data structures using C
Node tmp=head;
if(head==NULL)
{
printf("List is Empty\n");
return head;
}
head=headnext;
free(tmp);
return head;
}
Node deleteE()
{
Node tmp=head , p;
if(head= =NULL)
{
printf("List is Empty\n");
return head;
}
while(tmpnext!=NULL)
{
p=tmp;
tmp=tmpnext;
}
free(tmp);
pnext=NULL;
return head;
}
Node deleteS(int k)
{
int count=1;
Node tmp=head,p=tmp;
if(head= =NULL)
{
printf("List is Empty\n");
return head;
}
while(tmpnext!=NULL)
{
if(k==count)
{
pnext=tmpnext;
free(tmp);
}
p=tmp;
tmp=tmpnext;
count++;
}
68
Data structures using C
if(tmp==NULL)
{
printf("Invalid Position\n");
return head;
}
return head;
}
First Last
10 20 30 40
A circular linked list has no beginning and no end. Therefore it is necessary to establish the
First and Last node in such linked list.
First Last
10 20 30 69 40
Data structures using C
50 temp
First Last
10 20 30 40
tmp
50
70
Data structures using C
if(first = = NULL)
first = last = temp;
else
{
Lastnext = temp;
tempnext = First;
Last=temp;
}
}
71
Data structures using C
Advantages
Nodes can be accessed easily
Deletion of node is easier
Concatenation and splitting of circular linked list are more efficient.
Disadvantages
It may enter an infinite loop
Head node is required to indicate the First and Last of the circular linked list.
Backward traversing is not possible.
In this Left link points to the predecessor node and the Right link points to the successor
node. The structure for the doubly linked list is given below.
struct node
{
72
Data structures using C
int data;
struct node *left ;
struct node *right ;
};
typedef struct node Node;
Head
40 20 30
10
tmp
Node getnode( )
{
Node tmp;
tmp=(Node)malloc(sizeof(struct node));
tmpleft=NULL;
tmpright=NULL;
return tmp;
}
Insert_Node(Node head)
{
Node tmp;
tmp=getnode( );
tmpdata=ele;
if(head = = NULL)
{
head = tmp;
return head;
73
Data structures using C
}
tmpright = head;
headleft = tmp;
return head;
}
Head p tmp
10 20 30 40
Node getnode( )
{
Node tmp;
tmp=(Node)malloc(sizeof(struct node));
tmpleft=NULL;
tmpright=NULL;
return tmp;
}
Insert_Node(Node head)
{
Node tmp, p=head;
tmp=getnode( );
tmpdata=ele;
if(head = = NULL)
{
head = tmp;
return head;
}
While(pright!=NULL)
74
Data structures using C
p=pright;
pright=tmp;
tmp->left=p;
}
tmp Head
10 20 30 40
Delete_Node(Node head)
{
Node tmp;
if(head = = NULL)
{
printf(“ List is empty”);
return;
}
else
{
tmp = head;
head = head Rigth;
free(tmp);
headLeft=NULL
}
Head tmp p
10 20 75 30 40
Data structures using C
Delete_Node(Node head)
{
Node tmp, p=head;
if(head = = NULL)
{
printf(“ List is Empty”);
return;
}
while(p->right!=NULL)
{
tmp=p;
p=p->right;
}
p->right=NULL;
free(tmp);
}
Advantages
Insertion and deletion are simple as compared to other linked lists.
Efficient utilization of memory.
Bidirectional traversal helps in efficient and easy accessibility of nodes.
Disadvantages
Uses two pointer, hence there is a wastage of memory.
76
Data structures using C
10 20 30
Head node
Temp
10 20 30
Head node
80
newnode
77
Data structures using C
Temp
10 20 30
Head node
80
newnode
78
Data structures using C
Deleting a node from the Beginning
Algorithm
Step1: If the Right link of the head node is pointing to itsef then print the message “List is
empty” and return
Step2: Make the Right link of the head node to point to the second node and the Left link of
the second node point to the head node
Step3: Free the first node and return head node.
Temp
10 20 30
Head node
Temp
10 20 30
Head node
Tree
Level 0
A Root
Leve l
B C D
1
E F G I Level 2
H
Level 3
J K L
Terminal Node
or Leaf
80
Data structures using C
Tree Terminoloy
1. Root : It is a firsrt node in the hierarchical arrangement of nodes.In the above figure
A is root node.
2. Node : Each data item in a tree is called a node. And it is a basic structure in tree.It
contains a data and pointer field.
3. Degree of a node: It is a number of subtrees of a node in a given tree. In the above
figure
a. The degree of node A is 3
b. The degree of node B is 2
c. The degree of node C is 1
d. The degree of node D is 2
e. The degree of Node E J F K L I is having 0
4. Degree of Tree : I us the maximum degree of a nodes in a given tree. In the above
figure A has degree 3 which is maximum degree of a nodes in that tree.
5. Termial nodes: A node without having children or a node with degree zero is called
terminal node or leaf node.
6. Non- Terminal node: Any node except root node whose degree is not zero is called
non termial node.
7. Siblings : The children nodes of a given parent node are alled sibling or brothers.
In the above figure E & F are the siblings of parent node B.
8. Level: The root has always level 0 then immediate childrens are at level 1 and so on.
9. Edge : A line connecting two nodes.
10. Path : It is a sequence of consecutive edges from source to destination.
11. Depth : It is the maximum level of any node in a given tree.
12. Forest: It is set of disjoint trees. By removing its root node in a tree is called forest.
13. Parent.node: It is the immediate predecessor of a node. For example B is a parent
node for its children E & F
14. Ancestor of Node:The node n1 is said to be ancestor of node n2 if and only if n1 is
father pf n2. In above fig A is ancestor of node K.
15. Descendant Node:The node n2 is descendant of node n1 if and only if n2 is a child of
n1. In the above figure J is a descendant of a node B.
Binary Tree :
Definition: A binary tree is a finite set of data items which is either empty or consists of a
single item called the root and two disjoint binary tree called the left subtree and right
subtree.
In binary tree maximum degree of any node is at most two.
A
B C
G
D E F
H I
81
Data structures using C
3. The total number of edges in a complete binary tree with n terminal nodes is 2(n-1).
Strictl Binary Trees: If every non-terminal node in a binary tree consist of non empty left
subtree and right subtree, then such a tree is called strickly binary tree.
B C
D E
F G
B C
D E F G
H I J K E N O
L
M
B C
D E F G
H I 82
Data structures using C
Heap tree
Binary Search Tree : A binary tree has the property that all data elements in the left
subtree of node n are less than the contents of node n and all elements in the right subtree of
node n are greater than or equal to the content of node n, is termed as Binary search tree.
7 11
5 8 10 13
3 6
Struct btnode
83
Data structures using C
{
int data;
int left;
int right;
int father;
};
struct btnode bn[max];
84
Data structures using C
Inorder : DBEAFCG
Preorder : ABDECFG
Postorder: DEBFGCA
Constructing a Binary tree and perform inorder, preorder and postorder tree traversal.
85