Sei sulla pagina 1di 63

-:DATA STRUCTURE:Introduction to data structure:Data:Data is a set of elementary item [or] is a collection of information [or]

collection of facts and figures.


Data structure:The data structure deals with the study of how the data is organized in the
memory, how efficiently retrieve [or] recall from the memory and how
efficiently manipulated in the memory. [or] The logical [or] mathematical
model of a particular organization of a data is called data structure.
Abstract data structure :An ADT is a mathematical model of a data structure, it specifies the type
of data stored, the operation supported on them and the type of parameters
passed to the functions.
CLASSIFICATION:Data structure is classified into 2 types:1: Primitive Data Structure.
2: Non Primitive Data Structure.
1:Primitive Data Structure:These data structure can be manipulated directly by the machine
instructions [or] these are readily available in a programming language that
means they can be directly operated upon by programming instructions. The
storage structure of this data structure may vary from one machine to
another machine. The storage representation and possible operations on
these data structure are pre-defined.
Eg:- char, int, float, double, long, short, unsigned, signed, void.
2: Non-Primitive Data Structure:These data structure cannot be manipulated directly by machine
instructions [or] these are not available in a programming language i.e they
cannot be directly operated upon by programming instructions. The storage
representation and possible operations on these data structure are not predefined and the user has to define them. The different non-primitive data
structure are arrays, strings, queue, stack, files, tree, graph and linked list.

Again these non-primitive data structure are classified into 2 types:1: Linear Data Structure.
2: Non-Linear Data Structure.
1: Linear Data Structure:These data structure shows the relationship of logical adjacency
between elements.
Eg: Arrays, Strings, Queues, Stacks, File.
2: Non-Linear Data Structure:These data structure shows the relationship of other than adjacency
between the elements. Non-Linear data structure may exhibit either a
hierarchical [or] parent-child relationship.
Eg: Tree, Graph.
Operations on Primitive Data Structure:Some operations on primitive data structure are as follows,
1: Creation.
2: Selection [or] Access.
3: Updation.
4: Delete.
1: Creation:
This operation is used to create [or] allocate the storage space for a
particular data structure. This operation is normally performed with the help
of declaration statement available in the C-programming language.
Eg: int k = 10;
2: Selection [or] Access:This is the most frequently used operations and used to access the data
with in the data structure. In case of files the access can be sequential [or]
random depend upon the nature of files. This operation is normally
performed using the name of the structure.
Eg: Scanf( %d, k);
Printf( %d , k);
3: Update:This operation is used to change [or] modify the data in a data structure.
The assignment operation is a good example of an update operations.
Eg: k = 25; k + +; k - -;

4: Delete [or] Destroy:This operations is used to de allocate the memory block of a particular
data structure. In some languages this operations is not supported [or] it is
automatically performed. In C-language free( ) is used to destroy the
memory block.
Operations on Non-Primitive Data Structure:Some of the operations on the Non-primitive data structure are as
follows,
1: Traversing [or] Display.
4: Merging.
2: Sorting.
5: Inserting.
3: Searching.
6: Delete.
1: Traversing:It is a process of visiting [or] printing each element in the data structure
exactly once to perform certain operations on it.
2: Sorting:It is a process of amazing the data elements either in a ascending order
[or] descending order.
3: Update:This operations is used to process of finding the location of the given
element in the specified data list.
4: Inserting:It is a process of adding a new elements to the existing structure either
beginning of the list [or] ending of the list [or] middle of the list.
Most of the times this operations is performed by identifying the position
where the new elements to be inserted.
5: Merging:It is a process of combining the elements in two different data structure
into a single structure.
6: Delete:It is a process of removing an item from the given structure. Most of the
items, this operation performed by identifying the position to delete the
appropriate element. The deletion operation can be performed either
beginning of the list [or] end of the list [or] given position in the list.

Goals of Data Structure:1: We mean that a data structure is designed, to work correctly for all
possible input. The correctness will always depending on a specific problem,
the data structure is introduced to solve, but correctness should be a primary
goal of a data structure.
2: Efficient:
Use full data structure and their operations depends on the utilization of
the CPU time, memory , hardware resources, computational time.
3: Reversibility:The same source code be a component of different system in various
applications [or] situations. Developing quality software can be expensive,
and its cast can be reduced source what if the software is designed in a way
that makes it easily reusable in future applications. Software reuse can be a
significant cost saving and time saving technique.
4: Adaptability:Modern software projects such as developing word processed, web
browser, and internet such as engineers involve large software system that
are inspected to last for many years. Software needs to be able evolve over a
time in response to changing conditions. These changes can be expected in
CPU speed. Software should also be able to adopt to un expected events.
5: Robust:Every good programmer wants to produce software that is Robust,
which means that a program producers the correct output for all inputs.
Egg: If a program is expecting a number of to be input as an integer and
instead it is input as a float number [or] other than integer, then the
programmer can handle such uninfected results in the data structure.
Needs For Abstraction:Abstraction is a powerful concept in computer science the main idea of
this concept is to distill a complicated system down to its most fundamental
parts and describe parts in a simple, precise language [ using mathematical
and logical model ]. Typically describing the parts of as system involves
naming the different parts and describing their function origin.

-:PRIMITIVE DATA STRUCTURE:A bit pattern can be used to store different types of information .it may
represent character or Integer or Float or +ve or ve values.

Binary Number :
The binary number is a positional system as a decimal system .In the
binary system each bit position represent a power of 2.It consists of only two
elements o and 1.
Integer:
It is nthe whole or natural number ,which can be either +ve or _ve
number.
When we represent ve number using a binary system the notation is
known as either 1s compliment or 2s compliment .
The general representation of the integer as fllows,
Sign bit
Data bit
1
15
If the sign bit consists of 1 indicate ve integer otherwise +ve integer.
Fractions or Real Number Representation:
Real number consists of both integer and decimal part .Float and
Double data type are stored in mantissa and exponent format.
The number of bytes used to represent a floating point numbers depends on
precession of the variables.
The general format of Float data type as follows,
Sign bit
Mantissa
Exponent
1
8
25
The floating point number is also called precession float point number.
The double data type used for storing a very small ,very big number.
It is also called as double precession floating point , it gives 16 places of
accuracy.
The general format of double data type is as follows,
Sign bit
Mantissa
Exponent
1
11
52
The ASCII representation of a character uses 8 bit pattern for each
character .using 8 bit pattern to represents 256 different character with
different bit pattern.
The general format of Character is as follows,
Data bit
The pattern 01000001 ,it represent a character A and 01000010 represent a
character B .
In general the pattern 0100000101000010 represent a string AB.

POINTERS:
It is a data variable which allocates another variable address.
The compliment memory consists of storage shells . Each shell uses 1 byte
of memory space .Each byte in memory identified by sequence of starts
from 1 till end of memory . This sequence numbers called as address.
1. Access
2. Save the memory block.
3. Access bit, byte and word.
4. Faster accessing the data.
5. To stimulate function can return more than one values
6. Allocate and de allocate the memory block dynamically.
7. We can access CPU register directly.
DECLARATION OF THE POINTER:
;
Data type *pointer variable;
Where, data type is any valid or
derived data type.
*the pointer .
Pointer-variable is the user defined variable name.
Eg: int *k;
K is a integer pointer ,it can allocate integer variable address.
$ W A P to illustrate the pointer concept.
POINTER OF A POINTER:
It is a variable it can allocate the address of the another pointer variable.
It is denoted by ,
**variable-name;
$--> W A P to illustrate pointer of a pointer.

-:POINTER AND ARRAYS:


An array name simply means that starting address of the array.
Assume we declared an integer array n and string address is 2000.the
declaration as,
int k[10];

The memory representation as follows,


X
2000
10
2002
20

100

Just the array name indicates the starting address of the array. In other words
x means the address of the 1st element so &x[0] and x are refused as the
same location in the given array.
&x[1] and (x+1) are pointed to same memory block 2002.just x
referring the address 2000 and (x+1) referring the address is called as base
address. Adding 1 to an integer Pointer, will actually increase the pointer
value by 2,so that it can points to the next memory location . The address of
each element can be obtained as follows,
&x[0](x+0)(2000+0*2)
&x[1](x+1)(2000+1*2)
.
.
.
.
&x[4](x+4)(2000+4*2)
Where,2000 is the Base or starting address.
0,14 is the subscript .
2 is the scale factor.
In general &x[1](x+i) where i= 0,1,2.n.
The scale factor depends on the type of the data being stored ,
That means integer has 2 bytes . character has 1 byte , float has 4 bytes ,
double has 8 bytes of memory.
Eg : W A P to read an integer array elements and print the string using array
and pointer concept.

FUNCTION:
In C language two ways to call the function ,
1.Call by value.
2.Call by reference(address).

1.Call by Value:
It is argument passing mechanism. When the value of the arguments passed
to the functions, these are copied in to ht storage of the function parameters.
If the function parameters are modified then this will affect the content of
the arguments. When the function completes its execution ,the local values
are lost.

$--> A program to illustrate function call by value.


2.Call by reference(address):

It is a argument passing mechanism, when the address of the actual


argument are passed to the function ,the address are copied int to the storage
of the function pointer parameters. If the function parameters are modified
then this will effect the actual arguments.
$-->A program to illustrate to interchange 2 integer number using function
call by address concept.
$-->A program to find area of circle and circumference of the circle using
function call by address.
$-->A program to create user defined function concat and using pointer
variable.
$-->A program to find length of string and perform string concatenation
using menu driven program and pointer variable.

COPY OPERATION:
Copy operation of making one string to have the same value a another
string . In other words to make the duplicate of the existing string .
In C-language ,there is a built in function strcpy( ),it takes two
argument str1,str2.str1 is target string str2 is the source string.
Strcpy( str1,str2);
This function copies the content of str2 to str1.
Eg: srt2=computer
strcpy(str1,str2);
Out put is computer in str1.

$-->A program to create the user defined function to copy the


content of 1 string to another string and pointer variable.
SUBSTRING OPERATION:
This operation is used to extract a position of the string from a main
string. OR
It is a process to extract number of character from specified position in
the given string.
To perform this operation the user has to provide these arguments,
1: Main string .
2: Number of character to be extract.
3: The position of the 1st character in the string.
This operation is normally perform with the help of the function defined by
the user in the C language. The usage of the function is as follows,
Substr(string ,n,pos);
Where,

String main string.


nnumber of the character to be extract.
Posposition.
Eg: 1.substr(computer,3,2);
0/pmpu.
2.substr(computer,2,4);
o/put.
3.substr(computer,10,3);
0/pInvalid operation.
$-->W A P to create the user defined function to extract substring from the
main string using pointer variable.
$-->W A P to copy content one string to another string and substring
operation using menu driven program and pointer variable.

PATTERN MATCHING( INDEXING ):


Pattern matching is a process to check whether a substring is present in
a given string . OR
Indexing is a process to find the substring position in the main string .If
it is found identify the position otherwise generate an message substring
not found . This operation is normally perform with the help of a function
defined by the user in the C-language. The general format of the indexing is
as follows,
Index(str1,str2);
OR
Pattern(str1,str2);
Where index and pattern are the function name.str1 is the main string ,str2 is
substring .
This function takes two strings as an arguments such as an arguments
such the str position in the main string ,if found return the position otherwise
return (-1).
Eg: 1:Index(computer, put);
o/p 3.
2:Pattern(computer, pt);
o/p-1.
3:Pattern(put, computer);
o/psubstring length exceed.
4:Index(put, put);
o/p0.
$-->W A P to perform pattern matching operation using user defined
function and pointer variables.

MEMORY REPRESENTATION OF THE STRING:


The memory representation identifies the method using which a string
can be stored in the memory of the computer .
These are 3 methods my which string can be stored,
1: Fixed length method.
2: Variable length with fixed maximum method.
3: Linked list method.
Since a string contains a sequence of characters and each character
requires one memory location a string can be confidently represented by
using a sequence of memory locations.
1: Fixed length method:
In this method ,strings are stored in memory shells that are all of same
length ,the string will be allocated fixed number of storage locations,which
is decided even before the string is created.
The actual amount of the storage used by the string is known only when
the string is created.
Eg: In the C-language the data declaration as,
Char st[10];
Allocates 10 memory locations are allocated to ht string st. If the operations,
strcpy (st, ABC); is performed then only these storages spaces are utilized
and the remaining memory space is wasted [or] unused.

The pictorial representation of the memory shells as follows,


(String variable) St

Advantages:
1: Easy to implement.
2: Easy to access.
3: The string can be changed easily provided the length of the new string
does not exceed the fixed storage.
4: Easy to understand.
Disadvantages:
1: All the memory may not be utilize efficiently.
2: Wastages of the compilation time.

2: Fixed maximum length method:


In this method the string are stored in the memory shells, which all of
the same length, how ever one also knows the actual length of the string.
There is an information field which contains the length of the string and a
linked field contains the address of the memory shells [or] a string.
Memory map table:

Advantages:
1: Modification such as insertion[or] deletion are easier.
2: Efficient storage representation.
Disadvantages:
1: To remember the starting address [or] location.
2: The character [or] data cannot access directly in the middle of list.

String initialization:
1: At declaration stage.
2: At body of the program.
In each ways, their two method to initialize 2 variables, they are
A: Using character constant method.
B: Using string constant method.
1: At declaration stage:
A: using character constant method:
Any character enclosed in a single quote is called character constant. It
represents an ASCII value.
Char st[5]={u,s,e,r,\0};
St
U S E R \0

0 1 2 3 4
In the character constant method user forcibly introduce the null
character at end of the string.
B: using string constant method:
A stream of character enclose between double quote is called string
constant.
Char[5]= user;
U S E R \0
0 1 2 3 4
2: At the body of the program:
A: using character constant method:
In this method declare, string in declaration statement .
Initialize the variable in the body of program using character constant. This
method allows the user selective initialization [or] indivisual data data
member can be initialized.
Char st[5];
St[0] = s ; st[1] = t ; st[2] = a ; st[3] = r ;
B: using string constant method:
In this method allows the user to initialize by a library function
strcpy( ).
In this method the assignment is not allowed.
Eg: Char st[5];
Strcpy( st, star);
St

-:ARRAYS:Introduction:
A list is a finite ordered sequence of the data elements known as
elements. Ordered list have their elements positioned in ascending order of
values. Why an ordered list have no particular relationship between values.
A list said to be empty [or] under flow when it contains no elements. The
number of elements currently stored in a given list is known as the length of
the list > the beginning of the list is called Tail. If the list contains all the
elements is called as list is full [or] over flow.
List Implementation:
These are 2 standard approaches to implementing list,
1: Array based sequential list.
2: Linked list.

1: Array based sequential list:


Array based list implementation uses an array to store the elements of the
same list. This implies that an array of the same fixed size will be allocated
so the size of the array must be known when the list of object is created.
In this method stores the elements of the list in continuous array position.
Array position corresponds to elements position .
The possible operation on the array based list are:
A: Traversal [or] Display :
Processing each item in a array exactly once.
B: Search:
Find the location of a item in a given array.
C: Sorting:
It is a process of arranging data elements either ascending [or]
descending order.
D: Insertion:
Add a new element in to the array [size of array not changes].
E: Deletion:
Removing an element from an existing array[size of array not changes].
F: Merge:
Combine 1 [or] more array in to single array provided both arrays are same
type.

One Dimensional array :


An array is a linear data structure. It is a finite set of homogeneous data
elements of size n.
[or]
Array is a continues memory location, it can be store similar type of data
elements.
Data type arr-name[size];
Where, data type any valid basic [or] derived data type.
arr-nameuser defined array name.
size number of elements stored in given list.
Eg: int x[10];
X array of type integer.
Size of the array is called length of array.
The memory representation of array as follows,
0
1
2
3
4
5
6
7
8
9
100

102

104

106

108

110

The length of array is obtained by formula ,

112

114

116

118

Length [or] size == upper bond lower bond + 1.


== UB LB +1.
To calculate the length of above array as follows:
LB=0 , UB=9.
Length = 9 0 +1
= 10.
The array can be initialized in 2 ways,
1: At declaration stage.
2: At body of program.
1: At declaration stage:
In this case first initialize all the elements compulsory. If initialize only
few elements, remaining elements space fixed by zero.
Eg: 1: int S[5] = {10,20,30,40,50} ;
0 1 2 3 4
10 20 30 40 50
2:

int S[5] = {5,25 70};


0 1 2 3 4
5 25 70 0 0

2: At body of the program:


In this method user can be initialize all the elements [or] selected
elements. If the user initialize few elements remaining locations filled by
garbage collections.
Eg: int S[5] ;
S[0] = 10; S[2] = 25; S[4] = 70
0 1
2
3
4
10 -32 25 +32 70

Memory representation of single dimension [or] linear array:


Let x be a linear array of size n, it can be represented in the memory
by n sequential memory location. To access each memory location by the
formula,
Loc( x[k] ) == Base ( x ) + w( k LB );
Where, Loc( x[k] )is the address of x[k] in given array x.
Baseis address of x [or] starting address of array x [or] memory
address of x[0].

Wnumber of word per memory location [or] scale factor.


Consider an array x of size 10. suppose the stored at the starting address 100
with 2 words per memory.
To access the address of x[4] as follows,
int x[10];
size = UB LB +1
= 9-- 0 + 1 = 10.
Loc ( x[k] ) == Base (x) + W (k -- LB)
== 100 + 2 * (4 0) == 108.
Similarly to access the address of x[7] as follows
X[7];
Loc (x[k] )== 100 + 2 * (7 0)
== 100 + 14 == 114.
1:A: Traversing one [or] single dimensional array :
Traversing is a process of visiting each element exactly once and performing
some processing . [or]
Printing all the elements of array is known as traversing operation.
Algorithm for single dimensional array traversing ;
[ i loop control variable , n number of elements stored in given array ,
x array name ]
Step 1: start.
Step 2: [loop]
for i to (n-1) do
print x[i]
end for
Step 3: stop.
& W A P to find biggest of n numbers and position.
ALGORITHM:
[ s integer array , i loop control variable, nis no of element stored in
array ,bigstore biggest element from array, posbiggest element position]
Step 1: start.
Step 2: [read] n.
Step 3: [loop]
for i0 to (n-1) do
read ( s[i] )
end for

Step 4: [assign]
big s[0]
pos 0
Step 5: [loop] [find big and position]
for i 1 to (n-1) do
begin
a: [check]
if( s[i] > big) then
begin
[assign]
big s[i]
pos i
end if
end for
Step 6: print big and position
Step 7: stop.

Insert an element in to the given array:


Insert an element at the end of the array provided the memory space
allocated for the array is large enough to accommodate the additional
elements.
To insert an elements in the middle of the array [or] beginning of the
array ,then the average half of the elements must be move downward to new
locations to accommodate new element and keep order of the other element.
Write an Algorithm to insert an item into existing array:
[a[ ] integer array , n number of the elements stored in the array, pos
inserting position, item new element to be insert ,i loop control
variable]
Step 1:start.
Step 2: [read] item and pos.
Step 3: [loop]
for i n down to pos do
a[i] a[i-1]
end for.
Step 4: [assign]
a[pos] item.
Step 5: [increment]

n n + 1.
Step 6: stop.
$--> W A P to insert an item into array.

Deleting an item from the array:


To remove an item at the end of an array, the process is simple to remove
the last item and decrease the value of n. But deleting an element some
where in the middle of an array could requires the subsequent element to be
shifted upward in order to fill up the array elements.
Before deleting any item from the array, first check the condition. The
condition is the position is greater than n value, the condition is true print
an error message position invalid otherwise shift all the elements from
position to n location upward direction and decrement n by 1 step.
ALGORITHM:
[ a[ ] is an array, n is the number of elements stored in given array. Pos is
the position of elements to be delete . i loop control variable.]
Step 1:start.
Step 2:[read] pos
Step 3:[check]
if( pos < n) then
begin
a: print deleted item = a[pos].
b:[loop]
for ipos to (n-1) do
a[i]a[i+1]
end for.
c :[decrement]
nn-1.
End if.
step 4:stop.
$--> Write a program to delete an item from the given array.

Two dimensional array:


Two dimensional array is called tables in business application and
matrices in mathematics. Two dimensional m*n array x is a collection of

m*n data elements such that element is specified by pair of indices [such as
I] called subscript [or] index with the property that 0<=I<=m and 0<=j<=n.
The elements of x with first subscript I and second subscript j will be
denoted by a [I] [j]. This is a standard way of drawing two dimensional m*n
array, where the elements of x from a rectangular array with m rows and n
columns and where the elements a[i] [j] appear in row i and column j.
Eg: The array x has 3 rows and 4 columns as follows,
int x[3] [4] ;

Number of elements in the array x is 3*4 =12 elements.


The lower bound of the row and column of the matrix is 0.
Memory representation of the two dimensional array:
Two dimensional array has to be stored sequentially. Let x be the array
of size m*n. the number of elements of x array is m*n. That means, we
require m*n sequential locations to store the array x. These are two
methods to represent the two dimensional array ,they are,
1: Row major order.
2: Column major order.
1: Row major order matrix:
Let x be a two dimensional array of size m*n. In this method first row
elements are stored row elements then third row elements and so on.
Eg: consider an array x of size 3*4. The elements are
int x[3] [4] ;
storage representation as follows,

1000

02

04 1006

1008

10

12 1014 1016

18

20 1022

To access the address of the two dimensional array location as follows,


Loc ( x[i] [j] ) == Base (x) + W ( n[i] + j ).

Where, base starting address of array , w memory word [or] scale


factor , n number of columns in the matrix ,i and j index variable.
To find the address of x[2] [1] as follows:
Loc ( x[2] [1] ) == 1000 + 2 * (4*2 + 1)
== 1000 + 2* 9 == 1018.
2: Column major order matrix:
Let x be a two dimensional array of size m*n. In this method first
column elements are stored first then second column elements and so on .
Eg: Consider an array x of size 3*4 the elements are,
int x [3] [4];

The sequential memory representation as follows,

1000

02

04 1006

1008

10

12 1014 1016

18

20 1022

The formula to compute the address of the memory location in the given two
dimensional array of size m*n is given by,
Loc (x [i] [j] ) == Base (x) + W( m[i] + j)
Eg: To access the address of x [1] [3].
Loc (x[1] [3] ) == 1000 + 2( 3*3 + 1)
== 1000 + 2* 10 == 1020.
NOTE:
1: By default the memory representation of the 2 dimensional array is Row
major order matrix.
Advantages of arrays :
1: Sorting operation is very easy.
2: Binary search technique can be implemented by using array.
3: It is easy to complete the address of the elements in the given array.
4: To store matrix problems.
Application of arrays:
1: It is used to represent Record, stack, queue in memory.
2: It is used to represent the polynomial equations.

3: To arrange the data item either in ascending [or] descending order.


{sorting, searching [linear [or] binary search }.

Chapter -4

-:LINKED LIST:-

Structure:
Structure is a collection of heterogeneous data items [or] is a collection of
data items with different data types. It allows the user to create user defined
data type. It is also called as template. C-provides a way to collect different
data types together into a single entity is called structure. Using the structure
to create record type data structures.
Syntax:
Struct struct-name
{
data type member-1;
data type member-2:
.
.
.
data type member-3:
};
The definition of structure start with the keyword struct, followed by the
name of the structure. The name of the structure is unique to the structure.
The data member in the structure are called structure data member [or]
structure member, they are placed in a group between opening and closing
curly brace.
The structure definition is terminated by a semicolon( ; ), which is
followed by closed curly brace.
To create a structure variable with the following syntax,
Struct Struct-name var-list ;
Where, struct is a keyword, struct-name is a user defined structure name,
var-name is the user defined variable name.
Eg: To create a employ structure with the following information,
Employ , name, department , salary.
Struct emp
{
int emp ;
char name ;
char dept ;

int sal ;
};
Struct emp p ;
P is a variable of the type employ structure. It occupies 34 bytes in
memory space.
The memory representation of structure variable as follows,
p
eno name dept sal
100 xyz Sales 5700
<-------------34-------------->
To access the individual structure member with the following syntax,
Struct var .data member ;
Where, struct-var is the user defined structured variable,
. is the operator, it is called as structured member operator,
data member is the any structured member with define structure.
Eg: 1. To access the employ member from emp-structure as,
p.eno = 100 ;
similarly other data members.
p. sal = 5700 ;
strcpy ( p. name , xyz ) ;
strcpy ( p. dept , sales ) ;
$--> W A P to create a student structure, input and output the sale with
suitable format.
$-->W A P to create student structure, to read 5 student details and print the
same with the suitable format and find the highest mark student.

-:STRUCTURE AND FUNCTIONS:The structure variable are passed to the function either by,
A: by value method :To pass an argument to he function as entire structure value, the formal
arguments must be a structure variable of the same type, which is local to the
called function. To access the data member by structure member operator
[dot operator]. If any changes in the function it not affected to the original
value.
Struct book

{
int bno ;
char name[20] ;
int price ;
};
void main ( )
{
struct book p = { 100, Data structure , 180 };
clrscr( );
DISPLAY ( p );
getch ( );
}
DISPLAY ( struct book q )
{
printf ( \n Book number = % d , q. bno);
printf ( \n Book value = % d , q.name);
printf (\n Book price = % d , q.price);
q.price = q.price + 100 ;
printf (\n New price = % d , q.price);
}
B: by address method :The structure address passed to the function, the local argument must be a
structure pointer variable. Which is local to the called function. To access the
structure data elements by structure pointer member pointer[ ]. If any
changes in the function is affected to original value.
Struct book
{
int bno ;
char name [20] ;
int price ;
};
void main ( )
{
Struct book p = {100, Data structure,180};
clrscr( );
DISPLAY ( &p );
getch ( );
}
DISPLAY ( struct book *q )

{
printf ( \n Book number = % d , q bno);
printf ( \n Book value = % d , q name);
printf (\n Book price = % d , q price);
q price = q price + 100 ;
printf (\n New price = % d , q price);
}

Static and Dynamic memory allocation:Static memory allocation:While compilation time to allocate the memory block, such allocationis
called memory allocations.
Characteristics:
1: It is a fixed sized memory blocks.
2: Very difficult to perform insertion and deletions.
3: It is not required and predefined functions.
4: Wastages of memory blocks.
Eg: int a,b ;
int A[10] ;
char st[20] ;
[All ordinary declaration are array declaration].
Dynamic memory allocation:
While execution time [or] run time to allocate the memory block, such a
allocation is called dynamic memory allocation.
Characteristics:
1: It is a variable sized memory block.
2: Easy to insert [or] delete.
3: It requires a pre defined functions to allocate and de allocate the memory
block.
4: Memory blocks are utilized very efficiently.

Memory management functions:


This function dynamically allocate requested bytes from the map
memory(free memory area). This functions available under <alloc.h>. It
returns starting address of the memory block if it successful allocate the

required memory block otherwise return null value to the specified pointer
variable.
Syntax:
Ptr-var [ (type cast)]malloc( size );
Where, ptr-var is the pointer variable, type cast is the conversion
parameters, size is the required memory block.
Eg: 1: int *p ;
P = ( int * )malloc( 5 *size of(int) );
Malloc ( ) allocates the 10 bytes to the variable p with integer format.
p
1000
1002
1004
1006
1008
2: struct xyz
{
int a ;
char ch ;
float b ;
};
Struct xyz *p;
P = ( struct xyz * ) malloc ( sizeof ( structxyz ) );
p
a
ch
b
<-----2-----><-----1------><-----4------>
<---------------------7---------------------->
FREE ( ) :This function dynamically de allocate the memory block, which is
allocated by malloc ( ). This function is available under <alloc.h> header
file.
Syntax:
free ( p ) ;

$--> W A P to illustrate the dynamic memory allocation and de


allocation.

-:Linked list:A linked list represents a linear collection of items, called as node [or]
list. Node of a linked list can be searched about in the RAM memory, they

need not necessarily represent a set consecutive memory allocation. Each


node in a linked list has two parts, information part which contain the data
for node, link part [or] field which gives the memory address of the next
node in the list.
Types of linked lists:
1: Singly linked list. [SLL].
2: Doubly linked list. [DLL].
3: circular linked list. [CLL].

1: Singly linked list [or] SLL:A singly linked list node consists of two fields, first field is the
information field [or] info field, which contains the actual data [or] actual
information. The second field is the link [or] next field which holds the
address of the next node. The second field is always a structured pointer.
Structure definition and memory representation of singly linked list node
as follows,
Struct node
{
int info ;
struct node *next ;
};
node
info

next

<------2-------><------2------>
<---------------4--------------->.
Where, info is the information part, next is the linked part. The next variable
is referring the same node structure, such a reference is called self
referencing pointer [or] self addressing pointer.
A typical singly linked list as follows,
Start
p1
p2
------ 10 2000
20 3000
30 NULL
Primitive operations on SLL:1: Creating a linked list.
2: Traversing a linked list.
3: Inserting a node into the list.
4: Delete a node from the list.
5: Search a given element in the list.
6: Merging two [or] more list to from a single list.

1: Creating a singly linked list:-

$ write an algorithm and program to create and display


functions.
2: Traversing a linked list:Traversal is a process of visiting each node of the linked list exactly once
to perform some operations such as print the content of node.
In this case assign the starting address to the variable p1. check the p1
reaches to NULL value [or] not. If the p1 is not reaches to NULL value print
the content of node and p1 to next element.
Inserting a node into the list:Inserting is a process to add a new element into the existing linked list.
There are 3 types of inserting method they are,
1: Insertion a node at the beginning of the list.
2: Inserting a node at the end of the list.
3: insert a node at a given position in the list.
1: Inserting a node at beginning:The START pointer holds address of the 1st node of the linked list to
create a new node p2 and assign the information [or] item to the node. To
link the new node to the existing list by p2 next = START and re
arranging the start pointer.

ALGORITHM:
IAB ( ) Function:
1: START.
[allocate memory block].
2: P2 malloc ( sizeof ( struct node ) )
3: [assign]
info( p2 ) item.
next(p2) start.
start p2.
4: End of function.
IAB( int item )
{
P2 = (struct node *) malloc ( sizeof (struct node) );

P2info = item;
P2next = start;
Start = p2;
DISPLAY ( ) ;
}
2: Insert at end:In some of the applications we have to append an item at the end of the
list. To append an item to a linked list, is loop through the list until find the
element whose link the member points to NULL value.
We use a pointer p1, to traverse from the first node to last node. After
finding the last node to create a new node and assign the value. Connect the
new node to the end of list by p1next = p2.
Start
10 2000
Start
------ 10 2000
------

p1
20 3000
Before insert
p1
20 3000
After insert.

ALGORITHM:
1:Start
2: [locate the first node]
P1 start.
3: [find the last node] [loop]
While(next (p1) != NULL) do
[move the pointer to next node]
P1 next(p1).
End while.
4: [allocate new memory location]
P2 malloc( sizeof(struct node)).
5: [assign]
info(p2) item.
Next(p2) NULL.
6: [connect] or [join] or [link]
Next(p1) p2.
7:[ End of function].

p2
30 NULL
p2
30 4000

p4
40 NULL

Program:
IAE ( int item )
{
P1=start;
While( ( p1next) != NULL )
P1 = p1next;
P2 = ( struct node *) malloc ( sizeof( struct node) );
P2info = item ;
P2 next = item ;
P1 next = p2;
DISPLAY( ) ;
}
3: Insert at position:Suppose we are given the item, which has to be placed at a given position
in the linked list. First accept the item value and position. Move the pointer
p1 to the required position then insert now node p2 in to the existing list.
Steps:1: To find number of elements [or] node in the list.
2: To verify the position is valid [or] invalid.
3: If position equal to one call insert at begin function.
4: If the position equal to (count + 1) call insert at end function.
5: If the function lies between 2 to count the perform the following steps,
A: Find the position in the linked list that means locate p1 to position and
Previous node by t.
B: Allocate new memory location to the variable p2 and assign the item.
C: Insert the new node between t and p1.
ALGORITHM:1:Start.
2: [count number of nodes in list]
While( p1 != NULL) do
Begin
[increment]
Count ++
[move the pointer] p1 next(p1)
End while.
3: [check]
if( pos < 1 [or] pos > (count + 1) ) then

print invalid position


go to step 4.
else if ( pos = 1 )
[call function]
IAB ( item )
else if ( pos = ( count + 1) ) then
[call function]
IAE ( item )
else
a: p1 start , t start
b: [loop]
for i 1 to ( pos -1) do
begin
t p1
p1 next( p1 )
end for.
c: [allocate new memory location]
p2 malloc( sizeof ( struct node ) )
d: [join / connect]
next( t ) p2
next( p2 ) p1
end if .
4:[End of function].
Start
------ 10 2000

p1
20 3000

p2
30 4000

40 NULL

Start
------ 10 2000

20 5000

30 4000

40 NULL

50 3000
-:PROGRAM:IAP( int item , int pos )
{
int count = 0;

p4

struct node *t ;
p1 =start ;
while( p1 != NULL )
{
Count + + ; P1 = p1next ;
}
if ( ( pos < 1 ) !! ( pos > (count + ! ) ) )
{
Printf( invalid position ) ;
getch ( );
}
else if ( pos = =1)
IAB ( item );
else if ( pos = = (count + 1) )
IAE ( item );
else
{
P1=t= start;
for( i =1; i < pos ; i + + )
{
t = p1; p1= p1 next ;
}
P2 = ( struct node * ) malloc ( sizeof( struct node) );
P2info = item;
t next = p2;
p2 next = p1;
}
DISPLAY ( );
}

$ Write a program to create a singly linked list , Display and


insert an item into list using menu driven program.
-:Garbage collection:The operating system of a computer periodically collects all the deleted
space on to the free- storage list. Any technique which does this collection is
called garbage collection.
The garbage collection usually takes place in 2 steps first the computer
runs through all the list tagging those cells which are currently in use and

then the computer runs through the memory collecting all untagged space on
to the program.
The second method the operating system collects the free memory
blocks from them free storages collection and tagged into a list called as
garbage collection.

-:Deleting an item from the linked list:To delete an existing node from a linked list, we have to loop through
the node until we fixed the node we want to delete. We should follow the
steps to delete a node from a existing linked list.
1: If the linked list is empty then deletion is not possible and this condition
is called as under flow condition.
2: To delete a particular node, we have loop through the nodes until we find
the node we want to delete.
3: If the end of the list has been reach, position out of range message can be
displayed on the computer terminal.
Delete operation is classified into following types:
1: Delete at begin [or] Deletion of first node.
2: Delete at end [or] Deletion of last node.
3: Deletion of node at given position.

1: Delete at Begin:A: Check the list is empty [or] not.


B: Move the start pointer to next element.
C: Remove the previous node.
ALGORITHM:
1:Start.
2: p1 start.
3: [check]
if( start = NULL ) then
print Linked list is empty
goto step 4.
[Other wise]
A: [move start to next node]
Start next ( p1 )
B: [remove the node]
free( p1 )

end if.
4:[ End of function].
start
10 2000
1000

20 3000

30 4000

40 5000

2000

3000

4000

50 NULL
5000

Before deletion
start
20 3000
2000
P1

30 4000

40 5000

3000

4000

50 NULL
5000

After deletion
Program:DAB ( )
{
P1 = start ;
if ( start = = NULL )
{
Printf ( Linked list is empty); getch( );
}
else
{
Printf( Deleted item is % d , p1info);
Start = p1next;
free( p1 );
DISPLAY ( );
}
}.

2:Delete at end :To delete a last node of a linked list we have to the list from beginning to
end of the list and location the last node and its previous.
Steps:1: Check the list is empty [or] not.
2: Scan [or] traverse the pointer variable p1 to end of the list.
3: Locate the last node and its previous.
4: Disconnect the last node and renove.

-:ALGORITHM:1:Start.
2:[assign]
P1start.
3: [check]
if( start == NULL) then
print Linked list is empty
go to step 4.
Otherwise
A: [find last and its previous nodes]
While( next(p1) != NULL) do
Begin
t p1.
P1 next(p1).
End while.
B: print Deleted item is %d info( p1 ).
C: [disconnect the last node]
Next( t ) NULL.
D: [remove]
free( p1 ).
End if
4:[End of function].
start
10 2000
1000

20 3000
2000

30 4000

3000
Before deletion

40 5000
4000

start
10 2000
1000
Program:-

20 3000

30 4000

2000

3000

#include< stdio.h >


#include< conio.h >
#include< alloc.h >
Void main ( )
{
P1 = start;

40 NULL
4000

50 NULL
5000

if( start == NULL)


{
Printf( \n Linked list is empty);
getch ( );
}
else
{
While( p1next != NULL )
{
t = p1;
p1 = p1next ;
}
Printf ( \n Deleted item is %d , p1info );
t next = NULL;
free( p1);
DISPLAY ( );
}
}
3: Delete at position:1: Check the given list is empty [or] not.
2: If the list not empty then count the numbers of nodes.
3: Check the position is valid [or] invalid.
4: If the position is valid then check other 2 conditions,
A: If pos == 1
Call delete at begin position function.
B: If pos = = count
Call delete at end function.
5: To find [or] locate the position element by p1 and its previous by t.
6: Disconnect the deleted node and remove.
ALGORITHM:1:Start.
2: [check]
if( start == NULL ) then
print Linked list is empty.
Go to step 5.
End if.

3: [check position is valid [or] invalid].


if ( pos < 1 [or] pos > count) then
print Invalid position.
Go to step 5.
End if.
4: [check]
if ( pos = 1) then
[call function]
DAB ( )
else if ( pos = count ) then
[call function]
DAE ( )
else
A: [assign]
P1 t start.
B: [loop]
for i 1 to (pos-1) do
begin
t p1.
P1 next(p1).
End for.
C: [Disconnect and remove]
Next( t ) next( p1).
free( p1 ).
End if.
5:[End of function].
start
10 2000

20 3000

30 4000

40 5000

2000

3000

4000

1000

50 NULL
5000

Before deletion
start
10 2000

20 4000

1000

40 5000

2000

4000
After deletion.

-:Program:-

50 NULL
5000

Void main( )
{
int count = 0, i ;
p1 = start;
if( start == NULL)
{
Printf( \n Linked list is empty);getch ( ); return ;
}
While( p1 != NULL )
{
Count + + ; P1 = p1next;
}
if ( ( pos < 1) !! (pos > count) )
{
Printf( \n Invalid position); getch( ); return;
}
if ( pos == 1)
DAB( );
else if ( pos == count)
DAE( );
else
{
P1 = t = start ;
for( i = 1; i < pos; i ++)
{
t = p1;
p1 = p1next ;
}
Printf( \n Deleted item = %d , p1info);
t next = p1next; free ( p1);
}
DISPLAY( ) ;
}

End of the chapter linked list.

-:Polish notation:Expression:Expression is a valid combination of operator and operands. Operands


may be either a variable, constant [or] another expression. The operators are
unary, binary, ternary operator.
Polish notation:
It is a process of writing the operators in the expression either before their
operands [or] after them is called polish notation.
The operator placed before the operand is called prefix expression.
The operator placed after the operand is called postfix expression.
The operator placed between the operand is called infix expression.
This is the standard notation [or] expression.
Eg: A + B is the infix expression.
+AB is the prefix expression.
AB+ is the postfix expression [or] suffix expression.
To convert infix expression to prefix expression:
1: A + B * C .
A + T1 where T1= B * C = *BC.
T2
where T2 = A + T1 = +A T1.
+ A * B C is prefix expression.
2: A + B *( C/ D) + K.
A + B * T1 + K
where T1 = C/D = / C D.

A + T2 + K
where T2 = B * T1 = *B T1.
T3 + K
where T2 = A + T2 = +A T2.
T4
where T3 = T3 + K = + T3 K.
+ A T2 K
+ A * B T1 K
+ A * B / C D K is the prefix expression.
To convert the infix expression to post fix expression.
1: A + B * C.
A + T1
where T1 = B * C = B C *.
T2
where T2 = A + T1 = A T1 +.
AT 1 +
A B C * +.
2: A + B * ( C / D ) + K.
A + B * T1 + K where T1 = C / D = C D /.
A + T2 + K
where T2 = B * T1 = B T1 *.
T3 + K
where T3 = A + T2 = A T 2 +.
T4
where T4 = T3 + K = T3 K +.
T3 K +
A T2 + K +
A B T1 * + K +
A B C D / * + K + is the post fix expression.
To convert infix expression into post fix expression.
Procedure:Symbols Input precedence Stack precedence
G()
F()
+ , -1
2
*,/
3
4
$,^
6
5
Variables
7
8
(
9
0
)
0
#
-1
1: Initialize top = -1, i = 0, j = 0.
2: Push the symbol # to the top of the stack.
3: Read input symbol from left to right direction in the expression and
assign to the variable ch.
As long the precedence value of the symbol and top of the stack is greater
than the precedence value of the current ch value. If the condition is true
pop the item from the stack and place into postfix expression.

While( F( stack[top] ) > G[ch] )


Postfix [j] pop( )
j++
end while.
To check the precedence value of ch is not equal to the precedence
value of the stack element then push the ch value to the stack.
if ( F( stack[ top] ) != G [ch] )
PUSH ( ch )
End if.
Repeat the above procedure, if the input expression reaches to NULL
terminate the procedure.
Copy( pop ) all the elements from the stack except #, placed into
postfix expression.
While( stack[top] != # )
Postfix[j] = pop( )
j++
Algorithm:
[ infix[ ], postfix[ ], satck[ ] are the character array, ch is the character
variable, i and j are loop control [or] index variable, the top is the
integer variable, push( ) and pop( ) are the stack functions].
1:Start.
2: [read infix expression].
3: [assign]
top-1 , j 0copy
4: [call function]
PUSH( # )
5: [loop] for i 0 to infix[ i ] != NULL do
begin
A: [read a symbol from infix]
Ch infix[ i ]
B: [check the precedence value]
While( F(stack[top] ) > G[ch] )
Begin
1: [call function and assign]
Postfix[j] pop( ).
2: [increment]
j = j + 1.
End while.
C: [check]

if ( F(stack[top] ) != G[ch] ) then


[call function]
PUSH( ch )
End if.
End for.
6: [ copy the content of stack to prefix]
While( stack[top] != # ) do
Begin
A: [call function and assign]
Postfix[ i] pop( )
B: [increment]
j = j +1
end while.
7:[assign]
Postfix[j] NULL
8: print postfix.
9:Stop.
To convert Infix expression to prefix expression.
Procedure:Precedence value of symbols in input expression as follows,
Symbols Input
Output precedence
precedence
F( )
G( )
+ , -2
4
*,/
4
3
$,^
5
6
Variable
7
8
(
0
)
9
0
#
-1
1: Initialize top = -1.
2: Find the length of the infix and assign j & i.
3: Read input symbol from right to left in the infix expression.
4: As long as the precedence value of the ch [or] symbol is less than [or]
equal to the precedence value and top of the stack if the condition is true pop
an item from the stack and placed in the prefix from to left direction.
While( F(stack[top] ) > G[ch] )
Prefix[j] = pop( )
j-- --

end while.
5: If the while loop terminate check the condition if the precedence value of
top of the stack is not equal to precedence value of the symbol. If the
condition is true PUSH the input symbol to the stack. Repeat the above
procedure for all the item in the input expression.
6: Copy the remaining data elements from the stack except # to the prefix
expression from right to left direction.
While( stack[top] != #)
Prefix[j] = pop( )
End while.
Algorithm:[ infix[ ], prefix[ ], stack[ ] are the character array [or] string i & j are the
loop control variable [or] index variable, top is the integer variable PUSH( )
and pop( ) are the stack function, l is the length of the input [or]expression]
1:Start.
2: [read infix expression].
3: [calculate length]
L strlen(infix)
4: [initialize]
Top = -1, j L --1
5: [call function] PUSH(#)
6: [loop]
for i L1 down to 0 do
begin
a: [read symbol from infix expression]
ch infix[i].
b: [check the [precedence]
while( F(stack[top] ) > G[ch] ) do
begin
1: [call function and assign]
Prefix[j]pop( )
2: [decrement]
j j 1
end while.
c: [check]
if( F(stack[top] ) != # )
[call function]
PUSH( ch )
End if.

End for.
7: [copy remaining elements from stack to prefix expression]
While( stack[top] != # ) do
Begin
A: [call function and assign]
Prefix[j] pop( )
B: [ decrement]
jj -- 1
end while.
8: [convert prefix array to string]
Prefix[L] = NULL.
9: print prefix.
10:Stop.

Rank of the expression:


Suppose v is a set of operands [or] variables [or] constants.
V = { V1,V2,V3..Vn } and the set o is a collection of operators for
constructing an expression using elements of V. O = { O1,O2,O3Om}
The degree of an operator is defined as a number of operands associates with
that operator.
Eg: A + B is a binary arithmetic expression which consists of binary +
operator and associated 2 operands are A,B. The degree of operator + is 2.
Similarly, all the binary operators has the degree 2, all unary operator has
degree 1 and ternary operator has the degree 3.
We determine weather expression is valid [or] not, we calculate a rank ,
which is associated with each expression element.
The rank of the expression is determined as follows,
1: The rank of the symbol[ variables , constant] Vi is one [1].
2: The rank of an operator Vj is 1n, where n is the degree Oj.
3: The rank of an expression is the sum of the rank of the individual symbols
and operators.
The expression rank is one turn the expression is valid otherwise the
expression is invalid.
Eg: 1: A + B * C.
R[expression] = R[A] + R[+] + R[B] + R[*] + R[C].
= 1 + (-1) + 1 + (-1) + 1
= 1 - 1 + 1 - 1 + 1 = 1.
Above expression is valid.

2: A * B +
R[expression] = R[A] + R[*] + R[B] + R[+].
= 1 + (-1) + 1 + (-1).
= 1 - 1 + 1 - 1 = 0.
Above expression is invalid.

$ Write a program to convert the Infix expression to postfix


expression.
$ Write a program to convert the Infix expression to prefix
expression.
Evaluate postfix expression:Procedure:1: Read the postfix expression [valid expression].
2: Read the symbols [or] character from postfix expression starting from
Left to right direction.
3: Check the symbol [or] character. If the symbol is an operand [or]
alphabet push into the stack. If the symbol is an operator pop 2 data
element from the stack and assign to OP1 and OP2 respectively.
4:Depending on the operator to perform a mathematical operations and
to the stack .
5: Repeat the step 2 and 3 up to postfix expression character reaches to
the NULL value.
6: pop the top most element from the stack and placed into a variable
Res.
7: print the result.
Algorithm:[ postfix[ ], stack[ ] are the character array, i is the loop control variable, op1
and op2 are the operand, ch is the character variable, top is the integer
variable, Res is the result variables, PUSH and POP are the stack
functions.].
1:Start.
2:[read postfix expression].
3:[initialize].
top-1
4:[loop] read a symbol from postfix expression start from left to right.
for i 0 to postfix[i] != NULL do

begin
a: [read symbol]
ch postfix[i].
b: [check]
if ( isalpha(ch) or isdigit(ch) )
[call function]
PUSH( ch )
else
[ pop 2 element from stack]
1: op2 pop( )
2: op1pop( )
3:[perform mathematical operation]
Res op1 ch op2.
4: [call function]
PUSH( Res)
End if.
End for.
5:[ call function and assign]
Res pop( )
6: print Res.
7:Stop.
Trace postfix evaluation for given postfix expression.
1: ABC*+.
Where A = 4, B = 5, C = 7.
2: Convert this Infix expression to prefix then evaluate.
( 4 + 5 ) * ( 6 / 7 ).

$ Write a program to evaluate postfix expression.


$ Write a program to linked implementation of stack.
End of the chapter stacks

-:QUEUES:Queues is a special type of linear data structure. It works like first in first
out format[ FIFO]. The queues consists of 2 end , the insertion is takes place
at one end is called Rear end, and deletion takes places at the other end is
called Front end.
There are 4 types of queue system, they are
1: Ordinary queue.
2: Circular queue.
3: Priority queue.
4: Double ended queue.
1: Ordinary queue:In ordinary queue always, the data can be inserted at rear end and
deletion at front end.
These are 3 primitive operation can be performed on ordinary queue
they are
A: Insert [or] Insert at rear end.
B: Delete [or] Delete at front end.
C: Display [or] View.
The array representation of ordinary queue as follows,
Qsize = 5.
0
1
2
3
4

Front end
[deletion]

10

20

30

40

50
front

rear

1: Insert [or] Insert at rear end:To insert an item into the queue is called insert at rear end.
Before processing any operations in the queue, first initialize the queue size,
move front pointer to zero and rear pointer to -1. before inserting any item
into the queue, first check the queue is full [or] not, if the queue is full
display a message Queue is full [or] over flow otherwise increment the
rear pointer by 1 step and read the element at the rear location.
Algorithm:
[ Queue[ ] is an array element, queue size is the maximum element to be
allocated, r is the rear pointer, item is the data value].
Insert( item ).
1:Start.
2:[check]
if( r = (qsize 1) ) then
print Q is full [or] over flow.
Goto step 5.
3: [increment]
r++
4: [read the element]
Q[r] item
5:[End of function].
DISPLAY:To view the current status of the queue is called display [or] traversal.
Before display the content of queue first check the queue is empty or not. If
the queue is not empty display the elements from front pointer to rear
pointer. Otherwise print the message Queue is empty [or] under flow.
Algorithm:
[Q[ ] is an array, f is the front pointer, r is the rear pointer, i the loop control
variable].
1:Start.
2: [check]
if ( f > r) then
print Q is empty [or] over flow
go to step 4.
End if.
3: [loop] print the content of the queue.

for i f to r do
print Q[r].
end for.
4:Stop.
Delete operation:Removing an item from an existing queue is known delete operation. In
ordinary queue always the deletion can be takes places at front in , that is in
first in first out format.
Before deleting any item from the queue 1st check the queue is empty [or]
not. If the queue is empty display a message qeueu is empty [or] under
flow. Otherwise print the front element [or] deleted item and increment the
front pointer by 1 step.
Algorithm:[ Q[ ] is an array, f is the front pointer, r is the rear pointer].
1:Start.
2:[check]
if ( f > r) then
print queue is empty [or] under flow
go to step 5.
End if.
3: print deleted item is , Q[f].
4:[increment]
ff +1
5:Stop.

$ Write a program for the static [or] array implementation of


queue.
$ Write a program for the linked implementation of queue.
2: Circular queue:In an ordinary queue an item is inserted at the rear end and rear pointer
is incremented by one step. Once the rear pointer is reaches to queue size -1,
it display queue is full [or] over flow. To delete some element from the
queue then attempt to insert an item into the queue , queue display Q is full.
To over come this problem by another queue technique known as circular
queue.
The pictorial representation and its equivalent array representation as
follows,

Algorithm:
[Queue is an array, f is the front pointer, r is the rear pointer, Q size is the
total number of elements stored in the queue, count is the number of
elements present in queue].
Insert( ):1:Start.
2: [check]
if count = qsize, then
print Circular queue is empty
go to step 6.
End if.
3: [increment]
r ( r + 1) % qsize
4: [read data] q[r]
5: [increment] count count +1
6:Stop.
Delete ( ):[queue is an array, f is the front pointer, count is the number of element
stored in the array[queue], qsize is the maximum number of elements stored
in the queue].
1:Start.

2: [check]
if ( count = 0) then
print Circular queue is empty
go to step 6.
End if.
3: print deleted item = , q[r].
4: [increment]
f = ( f + 1 ) % qsize.
5: [decrement]
Count count 1.
6:Stop.
Display ( ):[ Q is an array, count is the number of elements present in the queue, i and j
is the loop control variables . f is the front pointer, qsize is the maximum
number of element stored in queue].
1:Start.
2: [ check]
if ( count = 0 ) then
print Circular queue is empty
go to step 5
end if.
3: [initialize]
jt
4: [loop]
for i 1 to count do
begin
a: print q[i].
b: [increment]
j ( j + 1) % qsize
end for.
5:Stop.

$ Write a program for the linked implementation of circular


queue.
3: Double ended queue:-

A queue data structure that supports insertion and deletion at both the
end [ front and rear] of the queue, such a queue is known as double ended
queue [or] dqueue.
A dqueue is a linear list in which elements can be added [or] removed
at either end but not in the middle.
Qsize = 5
front
0
1
2
3
4
rear
These are two variations of dqueue namely an input restricted dqueue
and output restricted dqueue which are intermediated between dqueue and a
queue.
The possible operations on double ended queue are as follows,
1: Insert at rear end.
2: Insert at front end.
3: Delete at front end.
4: Delete at rear end.
An input restricted dqueue which allows insertion at only one end of the
list but deletion at both ends of the list.
front
0
1
2
3
4
rear
An output restricted dqueue is a queue which allows deletion at one end of
the list but allows insertion at both ends of queue.
Q size = 5.
front
0
1
2
3
4
rear
4: Priority queue:A queue in which we are able to insert [or] delete an item from any
position depending on some priority is called queue.

Where A indicates administrative, B indicates technical, C indicates


supporters & D indicates user.
In the above queue the priorities of 1,2,3,4, have been attached to the
job of the administrators , technical, supporters and user respectively.
In general way we can say that a priority queue is a series of queue
respectively in situation in which it is known as priority ( priori ). Each
element is associated with queue elements.

Priority 1

Administrator
A1 A2 A3 --------------------------- An
Fa
Ra
Priority 2
Technical
B1 B2 B3 ---------------------------- Bn
Fb
Rb
Priority 3
Supporter
C1 C2 ---------------------------------- Cn
Fc
Rc
Priority 4
User
D1 D2 D3 D4 ---------------------- Dn
Fd
Rd
The priority queue can be visualized into 4 separate queues, each follow
first in first out format.
The elements in the second queue remove only when the first queue is
empty. Elements from third queue are removed only when the first and
second queue are empty and so on.

Disadvantages of representation the queues by linked list:1: A node in a linked list occupies more storage than array representation.
2: Processing time is more linked implementation when compare to array
Representation.
3: The linked implementation is slow compare to array representation.
Applications:
1: Message communication in computer network.
2: Real time system.
3: Time sharing system.
4: Circular queues is used in operating system.
End of the queue chapter.

-:TREE:Graph:A graph = ( v, e) where,


V is not a empty set of vertices and e is a set of edges. Vertices are
represented by a point a small circle. An edges can be represented by a
straight [or] curve line. Where e represents a set of ordered pair if and only
if, there is an edge from x to y with x--->initial vertex, y--->as terminal
vertex [or] node.

Set of vertices, v = { v1, v2, v3, v4 }


Set of edges, e = { e1, e2, e3, e4 } [or]
e = { (v1,v2), (v2,v3), (v3,v4), (v4,v1) }
Undirected graph:A graph in which every edge is undirected is known as undirected graph.

Directed graph [or] Di graph:-

A graph in which every edge is directed is known as directed graph.

Mixed graph:A graph is said to be mixed graph, if some edges are directed and
undirected.

Parallel edge:In a graph G a same pair of edge vertices are connected by more than one
edges are called as parallel edge.

In above graph G e1,e5 having same end vertices ( v1,v2 ).


Self loop:In a graph G an edge having both end vertices are same, such a edge is
called self loop.

Simple graph:A graph does not consists of a self loop and parallel edges, such a graph is
called simple graph.

Isolated graph:Any vertex in a graph G is not adjacent to any other vertices, such a
vertex is known as isolated vertex.

Degree:Number of edges entering a node is known as in degree of that vertex.


Number of edges leaving a node is known as out degree of that vertex.

A degree of vertex is sum of in degree and out degree of that vertex. It index
number of edges connected particular vertex.
Vertex
In degree + out degree = degree
V1
1
2
3
V2
2
1
3
V3
2
2
4
V4
1
2
3
V5
1
0
1
V6
0
0
0.
Circuit [or] Cycle:In a graph G one vertex say x is reachable from vertex y, vertex y is
reachable.
C = { v4, e4, v2, e2, v3, e3, v4 }.

-:Tree:Tree is a directed acyclic graph exactly one vertex having in degree zero
is called root node. Some vertices having out degree zero is called leaf [or]
terminal node. Some vertices having both in and out degree is zero. This
vertices are called internal vertices.

All the nodes that are present in left side of root node is left sub node. All
the nodes that are present in right side of root node is known as right sub
node.
Level:Level of any node x is given by the number of edges in path from root
node to current node. The level of root node is zero.

Level of 90 is 3
Level of 30 [or] 20 is 1
Level of 70 is 2
Level of 10 is 0
Height:Height of a tree is one more than the maximum level + one .
In above tree the maximum level is 3.
Height = 3 + 1 = 4.
Binary tree:It is a tree, in which out degree of each node either 0,1 [or] 2.

Strictly binary tree:It is a binary tree, in which out degree of each node either 0 [or] 2.
Completely binary tree:It is a binary tree, in which the number of nodes at any level i is 2 to the
power of i number of nodes.

Storage representation of binary tree:In computer binary tree can be represented in two ways,
1: Array representation.
2: Linked list representation.
1: Array representation:A: Convert the binary tree into complete binary tree.
B: Assign the array index to root node starting from zero in increasing
Order.
C: Process at each level from left to right direction.
D: Create an array of element of above size and assign the
Corresponding tree element to array location.

2:Linked list representation:A tree node consists of three fields, first field is pointer field [or] l child
[or] l link which holds the address of left sub tree. The second field is
information field which contains actual value stored in list. The third field is
pointer field holds the address of right child [or] link.
The structure of tree node and memory representation as follows,
Struct node
{
Struct node *Lchild ;
int info ;
struct node *Rchild :
};

Operations on binary tree:Some important operations can be performed on binary tree are,
1: Insert a tree node to the existing tree.
2: Tree traversal.
3: Searching a given node in a tree.
4: Copy the existing tree to another tree [or] duplicate the existing tree.
1: Tree traversal:EXPLAIN THE BINARY TREE AND TREE TRAVERSAL TECHINQUE

Tree traversal is the most common operation, performed on binary tree.


In this technique each node in the tree is process [or] visit includes print the
root node ]or] print the content of the root node. There are three traversal
technique [or] method to display the tree structure they are
A: Pre order.
B: In order.
C: Post order.
1:A: Pre order [ LVR ]:Pre order traversal of a binary tree can be recursively defined as
a: visit [or] print the root node.
b: traversal left sub tree in pre order [ root ---> Lchild ]
c: traverse the right sub tree in pre order [ root ----> Rchild ]
1:B: In order [ LVR ]:In order traversal of binary tree can be recursively defined as
a: process the left sub tree in in-order process [ root---->Lchild ]
b: visit the root node [or] print.
c: process the right sub tree in in-order process [ root---->Rchild]
1:C: Post order [ LVR ]:Post order traversal of a binary tree can be recursively defined as
a: traverse left sub tree in post order process.
b: traverse the right sub tree in post order.
c: visit [or] print the root node.
pre order [ VLR]:- 10 20 35 30 25 5 15
In order [ LVR ]:- 35 20 30 10 5 25 15
Post order [ LRV ]:- 35 30 20 5 15 25 10
Pre order[ VLR ]:- * + A B / C D
In order[ LVR ]:- A + B * C / D
Post order[ LRV ]:- A B + C D / *
All operands are placed in terminal node and operations are placed in root
node, such a tree is called expression tree [or] parse tree.

$ write a program to create a binary tree and display a tree


traversal technique.

#include<stdio.h>
#include<sdtlib.h>
#include<alloc.h>
Struct node
{
Struct node *Lchild ;
int info ;
Struct node *Rchild ;
};
Struct node *Root = NULL, *p1;
Char dir[20] ;
Void main ( )
{
int ch ; clrscr ( ) ;
while( 1 )
{
Printf( \n 1. for Insert \n);
Printf( \n 2. for Pre order \n);
Printf( \n 3. for Inorder \n);
Printf( \n 4. for Post order \n);
Printf( \n 5. for exit \n);
Printf( \n \n enter your choice \n);
Scanf( %d, &ch);
Switch( ch )
{
Case 1: INSERT( ) ; break;
Case 2: PRE-ORDER( ); break;
Case 3: INORDER( ); break;
Case 4: POST-ORDER( ); break;
Case 5: exit(0) ;
}
}
}
INSERT( )
{
int i;
p1= (struct node*)malloc( sizeof (struct node) );
printf( \n enter an information \n);
scanf(%d, &p1info);
p1Lchild = p1Rchild = NULL;

if( Root= = NULL)


{
Root = p1;
return;
}
Printf( \n enter direction \n);
Scanf(%d, dir);
Prev = NULL;
Cur = Root;
for(i=0;i<strlen(dir);i++)
{
if( dir[i] = =L)
{
Prev = cur;
Cur = curLchild;
}
else
{
Prev = cur;
Cur = curRchild;
}
}
if( cur = = NULL)
{
if( dir[--i] = =L)
prevLchild = p1;
else
prevRchild = p1;
}
}
PRE-ORDER( struct node *t)
{
if( t!= NULL)
{
Printf( %d, tinfo);
PRE-ORDER( tLchild);
PRE-ORDER( tRchild);
}
}

IN-ORDER( struct node *t)


{
if( t!= NULL)
{
IN-ORDER( tLchild);
Printf(%d, tinfo);
IN-ORDER( tRchild);
}
}
POST-ORDER( struct node *t)
{
if( t!= NULL)
{
POST-ORDER( tRchild);
POST-ORDER( tLchild);
Printf(%d, tinfo);
}
}
Binary search tree:A binary search tree is a binary tree in which each node in tree the value
of new node is less than root node placed in left sub tree element in right sub
tree are greater than [or] equal to the value of root node.
Every node in tree satisfy this condition is left and right sub trees are
exists.

$ write a program to create a binary tree and tree traversal


technique.
#include<stdio.h>
#include<stdlib.h>
#include<alloc.h>
Struct node
{

Struct node *Lchild;


int info;
struct node *Rchild;
};
Struct node *Root=NULL,*p1;
Void main( )
{
int ch; clrscr( );
while(1)
{
Printf( \n enter 1. for INSERT \n);
Printf( \n enter 2. for PRE-ORDER \n);
Printf( \n enter 3. for IN-ORDER \n);
Printf( \n enter 4. for POST-ORDER \n);
Printf( \n enter 5. for exit \n);
Printf( \n \n enter your choice \n);
Scanf( %d, &ch);
Switch(ch)
{
Case 1: INSERT ( ); break;
Case 2: PRE-ORDER( ); break;
Case 3: IN-ORDER( ); break;
Case 4: POST-ORDER( ); break;
Case 5: exit(0);
}
}
}
INSERT( )
{
int item; clrscr( );
printf( \n enter the information \n);
scanf( %d, &item);
p1=(struct node *)malloc(sizeof(struct node) );
p1info = item;
p1Lchild = p1Rchild = NULL;
if( Root= = NULL)
{
Root = p1;
return ;
}

Prev = NULL;
Cur = Root;
While( cur!= NULL)
{
if( item<curinfo)
{
Prev = cur;
cur = curLchild;
}
else
{
Prev = cur;
cur = curRchild;
}
}
if( item<previnfo)
prevLchild = p1;
else
prevRchild = p1;
}
PRE-ORDER( struct node *t)
{
if( t!= NULL)
{
Printf( %d, tinfo);
PRE-ORDER( tLchild);
PRE-ORDER( tRchild);
}
}
IN-ORDER( struct node *t)
{
if( t!=NULL)
{
IN-ORDER( tLchild);
Prinf( %d, tinfo);
IN-ORDER( tRchild);
}
}
POST-ORDER( struct node *t)

{
if( t!= NULL)
{
POST-ORDER( tLchild);
POST-ORDER( tRchild);
Printf( %d, tinfo);
}
}.

End of the chapter tree.

Potrebbero piacerti anche