SlideShare ist ein Scribd-Unternehmen logo
1 von 71
Downloaden Sie, um offline zu lesen
DATA
STRUCTURE
A. SIVASANKARI MSc., M.Phil., DCP.,
HEAD OF THE DEPARTMENT,
DEPT OF COMPUTER SCIENCE,
D.K.M. COLLEGE FOR WOMEN (AUTONOMOUS)
SAINATHAPURAM, VELLORE-1.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 2
ACKNOWLEDGEMENTS
It is my immense pleasure to offer my first and foremost gratitude to the
Almighty God for giving me the power to believe in myself and pursue my
dreams.
I would like to express my gratitude to my Father B.M.Arunachalam,
Mother A.Kalaiarasi and Brother Dr. A. Dineshkarthik for their love,
encouragement and support.
I offer my humble gratitude to our honourable Secretary
Mr.D.Maninathan, BE., for permitting me to bring out this book and for their
valuable advice.
I would like to extend my heartfelt gratitude to our beloved Principal
Dr.P.N.Sudha Ph.D., for permitting me to bring out this book and for their
valuable appreciation advice and blessings.
I wish to express my profound thanks to my Colleagues and my well-
wishers Dr.M.Sobia and R.Rajeshbabu for their moral support and
encouragement in making this book a reality.
I also thank all my Friends and Students who supported directly or indirectly
to bring out this book in good direction.
I am happy to express my thanks to the publisher and the entire team of
Publications, who have taken immense pain to get this book.
I wish our readers all the very best in their all endeavours.
SIVASANKARI
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 3
UNIT-I
DATA STRUCTURE
Data are represented by data values held temporarily within programs data area or
recorded permanently on a file often the different data values are related to each other. To enable
programs to make use of these relationship. These data values must be in an organized form. The
organized collection of data is called a data structure. The program have to follow certain values
to access and process.
An Organized collection of data is called data structure. Data may be organized in many
different ways, the logical or mathematical model of a particular organization of the data is
called structure.
Data Structure :
Organized data allowed operator alternative definition is
d=[DFA]->D means –Set of Domains
F Means-Set of Functions
A Means –Set of Axioms
A Triple set of DFA is called data structure which is denoted by Symbol d.
DIFFERENT TYPES OF DATA STRUCTURE (OR)
CLASSIFICATION OF DATA STRUCTURE
1.We may classify the data structures as Linear and Non Linear Data Structure. In Linear data
structure the data item are arranged in a linear sequence line an array. In a Non-Linear the data
item are not in a sequence an example of a Non-Linear data structure is TREE.
2.Data structure may also classified as Homogeneous(Ex: Array) and Non-Homogeneous(Ex:
Record) Data Structure).An Array is a Homogeneous Structure in which all elements are of same
type records are a common example of Non-Homogeneous data Structure.
3.Another way of Classifying data structure is a static or dynamic data structure .A Static
structure are one whose sizes and structures are associated memory locations are fixed at compile
time. Dynamic structure are one which expand or shrink required during the program execution
and their associated memory location change. Records are a common example of non-
Homogeneous data structure.
4. Another way of classifying data structure is primitive and non-Primitive. Another name of
Primitive data structure is standard data structure. Non-Primitive data structure is called as
composite.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 4
DATA STRUCTURE
PRIMITIVE[STANDARDDATA TYPE] NON-PRIMITIVE[COMPOSITE DATA TYPE]
EXAMPLE EXAMPLE
1. INT 1. FILE
2. REAL 2. LIST[LINEAR,NON-LINEAR]
3. LONG INT 3. STACK
4. STRING 4. ARRAY
5.QUEUE
PRIMITIVE DATA STRUCTURE
NUMBER SYSTEM [BINARY,OCTAL,DECIMAL,HEXA-DECIMAL]
Numbers are used symbolically to represent quantities of objects.
Number system such as Roman Number system, Positional Number System.
ROMAN NUMBER SYSTEM ------ I,II,III,IV
POSITIONAL NUMBER SYSTEM ------- Decimal, Binary number system
Example: 329-Decimal ------300+20+9
3*102
+2*101
+9*100
0,1,2 are Positional weights.
Example: 10110
1*24
+0*23
+1*22
+1*21
+0*20
COMPLIMENTS
 1’s ,2’s,9’s,10’s with examples.
INT
 Long int
 Short Int
 Signed
 UnSigned
FLOATING POINT
 Real Number
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 5
CHARCTER INFORMATION
 BCDIC and ASCII
LOGICAL IMMPLEMENTATION INFORMATION
 And
 OR
 Not
NON-PRIMITIVE DATA STRUCTURE
Non-Primitive Data structure can be classified as Arrays, List and Files.
ARRAY
1. An Array is an ordered set which consist of a fixed number or objects.
2. No deletion or insertion operations are performed on arrays. At best elements can be
changed to a value which represents an element to be ignored.
List
1. A List is an ordered set consisting of a variable number of elements to which insertion
and deletion can be made.
2. A List which displays the relationship of adjacency between elements is said to be linear.
And other List is said to Non-Linear.
Data
Data is a element such as number,character etc…
[information raw data fact]
Field
A collection of data is called as Field
[name, sex..]
Record
A Collection of field is called Record
File
A Collection of record is called as file
Stack
Last in First out
Queue
First in first out
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 6
OPERATION ON DATA STRUCTURE
1. CREATION
An operation frequently used in conjunction with data structure is one which create a data
structure. This operation will be called CREATION Operation.
2. DESTROY
One which destroys the operation, the operation is called DESTROY Operation.
3. SELECTION [access]
The most frequently used operation associated with data structure is one that the
programmer uses to access data within a data structure. This type of operation is
known as SELECTION Operation.
4. UPDATE [Changing the Data]
Another operation used in Conjunction with data structure is one which changes
data structure.
This operation will be called an UPDATE.
ASYMTOTIC NOTATION [0,Ω,Θ]
1. [Big ‘oh’] The function f(n)=o(g(n)) (Read as f of n is big oh of g of n) if(if and only
if)their exist positive constants c and n0 .Such that f(n)<=c*g(n)) for all n, n>=n0.
2. [Omega] The function f(n)= Ω(g(n)) (Read as f of n is omega of g of n)if their exist
positive constant c and n0.such that f(n)>=c*g(n) for all n, n>=n0.
3. [Theta] The function f(n)= Θ(g(n)) (Read as f of n is Theta of g of n)if there exist +ve
constant c1,c2 and n0 .such that c1,g(n)<=f(n)<=c2g(n) forn,n>=n0.
4. [Little ‘oh’]The function f(n)=o(g(n)) (Read as of n is Little oh of g of n)if ,
𝑛 → ∞ 𝑓(𝑛)/g(n)=n->∞
𝑓(𝑛)
𝑔(𝑛)
= 0
5. [Little Omega]The function f(n)=w(g(n)) (Read as ‘F of n is little omega of g of n’)if,
lim n → ∞
g(n)
f(n)
= 0
ARRAY
1. Array is an ordered set which consists of a fixed number of objects.
2. No deletion or insertion operations are performed on array. At best elements can be
changed to a value which represent an element to be ignored.
3. Array can be classified as one dimensional, two dimensional and Multi-dimensional.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 7
ONE –DIMENSIONAL ARRAY
The simplest form of an array is a one dimensional array or vector the various element of
an array are distinguished by giving each piece of data separate index or subscript. The subscript
of an element designate its position in arrays ordering. An array named which consists on N
elements can be depicted as shown in figure.
Representation of a Vector
LO-1 1
Where Lo=> is starting Position
C=> Mention the type of array
.. i=> Finding Position Member
Lo+c(i-1)-->A[i]---- A[i]
Another Representation
A(1)
A(2)…………………………………………………………………….A(n)
If we want to find A[10]
Loc a[5] = L0 + c * (I-1)
= 1 + 1* (5-1)
5 = 1 + 4
5 = 5
TWO DIMENSIONAL ARRAY
Any Array Defined To Have More Than One Dimension Is Considered To Be Multi
Dimensional Array. An array can be 2,3,4 or N dimensional array.
Two dimensional arrays, sometimes called matrices. This array is to visualize a table
column and rows. The first dimension in the array refer to the row, and the second dimension
refers to the columns.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 8
Example: A Collection of data about the grades of students in a class in the four different
exams can be represented using a two dimensional array. If we have 10 students and each given
grades in 4 exams, we can depict it as in the table(fig 2)
Grade
Student Number
Each cell in this table contains a grade value for the student number (given by the
corresponding row number) and exam number)(g and exam number)(given by the corresponding
column number). An array A of order [0*4.A[I,j] represent an element of A. Where I runs from
to 10 and J runs from 1 to 4 A[3,4]]will have the grade value of 8th
Student in first exam and so
on.
[Loc A[I,j]=L0 + (i-1) *(j-1) ]
In General an array of the order M*N consist of M rows, N Columns and MN elements.
It may be depicted as
1 , 2 , ……………………………………………….N
1
2
.
.
M
OPERATIONS AN ARRAY
The array is homogeneous structure (I,e) the element of an array are the same type .
Following set of operations are defined for this structure.
1. Creating an array
2. Initializing an array
3. Storing an element
4. Ret riving an element
5. Inserting an element
1 2 3 4
1
2
3
4
5
6
7
8
9
10
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 9
6. Deleting an element
7. Searching for an element
8. Sorting element
9. Printing an array
STORAGE OF ARRAYS IN MAIN MEMORY
The data represented in an array is an array is actually stored in the Memory cells of the
machine Because computer’s memory is linear, a one dimension array can be mapped. Onto
the memory cells in a rather straight forward manner. Storage for element A[I+1] will be
adjacent to storage for elements BCD for I=1 to n to find the actual address of an elements .
One Merely needs to subtract one from the position of the desired entry. And then add the
result to the address of the first cell in the sequence.
Two dimensional array, we think of data being arranged in rows and columns. However
machine’s memory is arranged as a row of memory cells. Then the rectangular structure of a
two dimensional array must be stimulated. We first calculate the amount of storage area
needed and allocate a block of contiguous memory cells of that size on way to score the data
in the cells is row by row. That is we store first, the first row of that array and the second row
of the array and then the next and soon.
For Example :- The array defined by a which logically appears as given in figure.
Int [3][4]
A[0][0] A[0][1] A[0][2] A[0][3]
A[1][0] A[1][1] A[1][2] A[1][3]
A[2][0] A[2][1] A[2][2] A[2][3]
A[0][0] A[0][1] A[0][2] A[0][3]
A[1][0]  A[1][1] A[1][2] A[1][3]
A[2][0] A[2][1] A[2][2] A[2][3]
Appears physically as given in row major representation. Such a storage scheme is called
row major order. The other alternative is to store the array column by column, it is called
column, it is called column major order.
A[0][0] A[0][1] A[0][2] A[0][3]
A[1][0] A[1][1] A[1][2] A[1][3]
A[2][0] A[2][1] A[2][2] A[2][3]
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 10
OPERATION ON ARRAY
1. To find the location
 Single Dimensional
 Two Dimensional
SINGLE DIMENSIONAL
EXAMPLE: FORMULA: Loc A[i]= L0 + c *I – 1
A[10]=A[0],A[1],----------------------a[9]
To Find the Location of a[5]
Loc A[i] = L0 + C * I – 1
Where I = Position of the Location
L0 = First Position of Array
C = Mention the dimensional type
Loc A[5]= L0 + c * (i-1)
A[5]= 1 +1 * [5-1]
A[5] = 1 + 1 * 4
A[5] = 1 + 4
A[5] = 5
TWO DIMENSIONAL ARRAY
Row Major Order : Loc A[I,j]=L0 + [i-1] *n + (j-1)
Column Major Order : Loc A[I,j]=L0 + [j-1] *m+(i-1)
Where i = Row Position
J= Column Position
m=row of the given matrix
n=Column of the given matrix
Lo= 1 st
Position of the given matrix
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 11
The given matrix is [6,4]
Representation of given matrix = A[1][1]A[1][2]A[1][3]A[1][4]
A[2][1]A[2][2]A[2][3]A[2][4]
A[3][1]A[3][2]A[3][3]A[3][4]
A[4][1]A[4][2]A[4][3]A[4][4]
A[5][1]A[5][2]A[5][3]A[5][4]
A[6][1]A[6][2]A[6][3]A[6][4]
ROW MAJOR ORDER
Loc A[I,j]=L0 + [i-1] *n + [j-1]
Loc A[3,2] = 1 + [3-1] * 4 +[2-1]
= 1+ 2 * 4 + 1
= 1 + 8 + 1
Loc A[3,2] = 10
COLUMN MAJOR ORDER
The Given matrix is [6,4]
Representation of Given matrix = A[1][1] A[1][2]A[1][3]A[1][4]
= A[2][1]A[2][2]A[2][3]A[2][4]
= A[3][1]A[3][2]A[3][3]A[3][4]
= A[4][1]A[4][2]A[4][3]A[4][4]
= A[5][1]A[5][2]A[5][3]A[5][4]
= A[6][1]A[6][2]A[6][3]A[6][4]
Loc A[I,j] = Lo + [j-1]m + [i-1]
Loc A[3,2]= 1 + (2-1) 6 + (3-1)
Loc A[3,2]= 1 + 6 + 2
Loc A[3,2] = 9
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 12
UNIT – II
STACK AND QUEUE
NON-PRIMITIVE DATA TYPE
STACK
One of the most important linear data structure of variable size is the stack.
Example : Pile of Tray (pile-stack)
DEFINITION
In the most general form of a linear list we are allowed to delete an element from and
insert on to any portion in the list. An important subclass of lists permits the insertion on deletion
of an element to occur only at any end.
A Linear list belonging to the subclass is called a stack.
This insertion operation is referred to as PUSH and the deletion Operation as POP. The
most and the least accessible elements in a stack are known as top and bottom of the stack
respectively.
Since insertion and deletion operations are performed at one end of the stack, the
elements can only be removed in the opposite order from that in they were added to the stack.
A Linear list is frequently referred to as a LIFO List, Which means “LAST IN FIRST OUT”.
Example: A common example of a stack phenomenon which permits the selection of only its end
element is a pile of trays in Cafeteria.
DIAGRAM REPRESENTATION
TOP TRAY OF FILE
Stacked Trays
Spring
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 13
Another example of a stack is a railway system for shunting cars as shown in the
diagram.
In this system the last railway can to be placed on the stack is the first to leave. Using
repeatedly the insertion and deletion operation permits that cars, to be arranged on the output
railway line in various orders.
OUTPUT DELETION
STACK
The operation on a stack are stimulated by a vector consisting of some large number of
elements which should be sufficient in number to handle all possible insertions likely to be made
to stack. A Pointer top keeps track of the top elements in the stack. Initially when the stack is
empty top has a value ‘0’ and when the stack contains a single element top has the value ‘1’ and
soon. Each time a new elements is inserted in the stack, the pointer is incremented by 1, before
the element is placed on the stack.
The pointer is decremented by 1,each time the deletion is made from the stack.
Bottom of stack
Vector of elements
representing a stack Top of Stack
Unused Stack
A more suitable representation of a stack is given in the stack represent the top element.
The left most occupied element of the stack represent its bottom element.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 14
ALTERNATIVE REPRESENTATION OF STACK
DELETION
INSERTION
BOTTOM TOP UNUSED STACK
OPERATIONS ON A STACK
The algorithm for insertion and deleting an element from a stack are given below
1. PROCEDURE PUSH(S,TOP,X)
This procedure inserts an element a to the top of a stack which is represented by a vector
s containing N elements with a pointer top denoting the top elements in the stack.
1. [Check for stack overflow]
If top>=N
Then write (Stack Overflow)
Return
2. [Increment Top]
TopTop +1
3. [Insert element]
S[Top] x
4. [Finished]
Return
2. FUNCTION POP(S,TOP)
This function removes the top element from a stack which is represented b a vector a and
returns this element. Top is a pointer to the top element of the sack.
1. [Check for underflow on stack]
If Top=0
Then write(STACK UNDERFLOW ON POP)
Take action in response to underflow
Exit
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 15
2. [Decrement pointer]
Top  Top-1
3. [Return for met top element of stack]
Return (S[top+1])
4. [Finished]
3. FUNCTION PEEP(S,TOP,I)
Given a vector S (Consisting of N elements S) represent a sequentially allocated stack
and a pointer top denoting the top elements of the stak. This function return the value of
the I th element from the top of the stack. The element is not deleted by this function
1. [Check for stack underflow]
If Top- I + 1 <=0
Then write (STACK UNDERFLOW ON PEEP)
Take action in response to underflow
Exit
2. [Return I th
element from top of stack]
Return (S[Top – I + 1])
4. PROCEDURE CHANGE (S,TOP,X,I)
As before a vector S(containing of N elements)represent a sequentially allocated
stack and a pointer top denotes the Top element of the stack. This procedure changes the
value of the Ith
element from the top of the stack to the value contained in X.
1. [Check for stack underflow]
If Top – I + 1 <=0
Then write (STACK UNDERFLOW ON CHANGE)
Return
2. [Change I th
element from Top to Stack]
S[TOP – I + 1] X
3. [Finished]
Return.
APPLICATION OF STACK
The first application deals with recursion. The second application of a stack is classical, it
deals with the compilation of infix expressions in to object code
1. RECURSION
A property or a set P can be specified by an inductive definition. An inductive definition
of a set can be realized by using a given finite set of elements. A and the following three classes
:Basis, inductive and external class.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 16
A Vector Representation Of n Stack
S[1]---------------------------------------------------------------------------------------------S[M]
B[1]+[1] B[2]+[2] B[N]+B[N] B[N+1]
The factorial function, whose domain is natural number, can be recursively defined as,
1 IF N = 0
FACTORIAL = N * FACTORIAL(N-1) OTHERWISE
Here FACTORIAL(N) is defined in terms of FACTORIAL(N-1) which in turn is defined
in terms of FACTORIAL(N-2) etc. Until finally FACTORIAL(0) is reached, whose value is
given as “ONE”. A recursive definition of a set or process must contain an explicit definition for
particular vales(s) of the argument(s).Otherwise the definition could never change.
An important facility available to the program is the procedure (function or subroutine).A
procedure that contains a procedure call to itself, or a procedure call to a second procedure which
eventually causes the first procedure to be called is known as “Recursive’ procedure.
There are two conditions that must be satisfied by and recursive procedure.
1. Each time a procedure calls itself (either directly or indirectly) it must be nearer in
some sense to a solution. In the case of the factorial function, each time that the
function calls itself its argument is decremented by ‘ONE’. So the argument of the
function is getting smaller.
2. Second , there must be a decision criterion for stopping, the process or computation.
In the factorial function the value of n must be zero.
There re essentially two types of recursion. The first type concerns recursively
defined function.(or primitive recursive function)an example of this kind is the
factorial function. The second type is recursion). A typical example of this kind is
Ackerman’s function which is defined as,
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 17
N+1, if m=0
A(M,N) = A(M-1 , 1 ) , if n= 0
A (M -1), A(M, N-1), OTHERWISE
Primitive recursive function can be solved iteratively.
A Iterative process can be illustrated with the aid of the flow chart given below:
There are four parts in this process,
1. Initialization
2. Decision
3. Computation (Calculation)
4. Updation (Change)
Initialization
The parameters of the function and a decision parameter in this part are set to there initial
values. The decision parameter is used to determine when to exit from loop.
Decision
The Decision parameter decides whether to remain in the loop.
Computation
The Required computation is performed in this part.
Updation
The decision parameter is updated and a transfer to the next iteration results. Recursion is
becoming increasingly important in symbol manipulation and non-numeric applications.
Done
Not
Not Done
ENTRY
INITIALIZATION
DECISION
COMPUTATION
RETURN
UPDATE
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 18
The general algorithm model for any recursive procedures contain the following steps:
1. [PROLOGUE] Save the parameters, local variables and return address.
2. [BODY]I f the base criterion has been reached then perform the final
computation and goto step3,Otherwise perform the partial computation and goto
Step1.
3. [EPILOGUE]Restore the most recently saved parameters local variable and
return address, go to this return address.
A Flow chart model for this algorithm is given the model consists of a prologue,
a body and an epilogue. The purpose of the prologue is to save the formal
parameters, local variable and return address and that of epilogue is to restore
them. Note that the parameters, local variables and return address that are restored
are those which were most recently(i.e) the last saved are the first to be restored
(LIFO). The body of the procedure contains a procedure call to itself. In fact,
They may be more than one call to itself in certain procedures.
The keybox contained in the body of the procedure is the one which invokes a call
to itself. The dotted-line exit from this box indicated that a call to itself is being
initiated within the same procedure. Each time a procedure saves all necessary
information required for its proper functioning.
4. The procedure body contains two computation boxes namely, the partial and final
computation boxes frequently the partial computation box is combined with the
Values of the arguments. The procedure call box(Updation box).
(This is case for computation of the factorial function).
The final computation box gives the explicit definition of the process for same
values or values of the arguments. The test box determines whether the arguments
values(s) in that for which explicit definition of the procedure is
given,[Characteristic associated with each call to(entry into a recursive procedure
is a level number. The entry in to the procedure due to the initial call from the
main program is given the level number ‘one’ as the main program is assumed to
have level number ‘Zero’. Each subsequent entry in to the procedure has an
associated level number ‘one’, higher than the level number of the procedure
from which the call was made. Another characteristic of the recursive procedure,
in the depth of recursion, which is the number of times the procedure is called
recursively in the process of evaluating a given argument or arguments, usually
the quantity is not obvious, except in the case of extremely simple recursive
functions. Such as factorial(N) for which the depth is N.
5. The last -in and first-out characteristic of a recursive procedure suggest that a
stack is the most obvious data structure to use to implement step1 and three of this
procedure. At each time procedure call (or level of recursion) the stack is pushed
to save the necessary values, upon exit from that level, the stack is pushed to save
the ‘popped’ to restore the saves values of the proceeding (or calling level).
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 19
The recursive mechanism is best described by an example. Consider as algorithm
to calculate factorial(N)recursively which explicitly shows the recursive frame
work.
FACTORIAL
Given an integer N, this algorithm computers N. The stack A is used to store an
activation record associated with each recursive call. Each activation records contains the current
value of N & the current return address (RET-ADDRESS). TEMP-REC is also a record which
contains two variables (PARM and ADDRESS). This temporary recorders required to simulate
the proper transfer of control from one activation record of algorithm FACTORIAL to another.
Whenever a temp-rec is placed on the stack A, copies of PARM and ADDRESS are
pushed on to A and assigned to N and RET-ADDRESS respectively. Top points to the top
element of stack A and its value is initially 0.
Initially ,the return address is set to the main calling address.(i.e. ADDRESSMain address)
PARM 2 is set to the initial values of N2.
1. [save N and return address]
Call PUSH[A,TOP,TEMP-REC]
2. [Is base criterion found]
If N=0 then
Go to step 4
Else
PARM N-1
ADDRESS step 3
Go to step 1
3. [Calculate N]
FACTORIAL N * FACTORIAL
4. [Restore previous N and return address]
TEMP-RECPOP(A,TOP)
(i.e., PARM N)
ADDRESS RET-ADDR
Go to ADDRESS
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 20
EXAMPLE
LEVEL NO DESCRIPTION STACK A CONTAINS
1 1.PUSH[A,0 (2,MAIN ADDRESS)]
2.If n≠0
PARMN-12-1==>1
ADDRESS STEP 3
TOP VALUE
2 1.PUSH [A,1(1,STEP 3)]
IF N≠ 0
PARMN-11-1==> 0
2. ADDRESS STEP 3 TOP VALUE
Top
3 1. PUSH[A,2(0,STEP 3)]
2.N=O
FACTORIAL1 TOP
Top
RETURN 4. TEMP.RECPOP(A,STEP 3)
ENTER LEVEL 2 3.FACTORIAL1 *1
4.TEMPPOP(A,STEP 3)
GO TO STEP 3
Top
RETURN
ENTER LEVEL 1 5.FACT2*1==>2
TEMP REC-POP(A,MAINADD)
GO TO MAIN ADDRESS
Top
2 1
Main
Add
Step 3
2 1 0
Main
Add
Step 3 Step 3
2 1
Main
Add
Step 3
2
Main
Add
2
MAIN ADDRESS
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 21
PROGRAM FOR FACTORIAL
# INCLUDE <IOSTREAM.H>
VOID MAIN()
INT FACT=1,N,I;
CIN>>N;
FOR(I=1,I<=N;I++)
FACT=FACT*I;
}
COUT<<FACT;
}
2. TOWER OF HANOI
Another complex recursive problem is that of the tower of Hanoi has a historical basis in the
virtual of the ancient tower of Brahma. The Problem is as follows
Given N discs of decreasing size stack on one needle and two empty needles, it is
required to stack all the discs onto a second needle in decreasing order of size. The third needle
may be used as Temporary Storage.
The movements of disc is restricted by the following rules,
i) Only one drive may be moved at a time.
ii) A Disc may be moved from any needle to any other
iii) At no time may a larger discs rest upon a smaller disc.
PICTURE OF HANOI
(A) (B) (C)
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 22
STEPS ARE
1. A TO C
2. A TO B
3. C TO B
4. A TO C
5. B TO A
6. B TO C
7. A TO C
The solution on this problem is most clearly seen with the aid of induction. To move one
disc, merely move it from needle A to needle C. To move two disc, move the first disc to needle
B, move the second from needle A to needle C, then move the disc from needle B to C.
In general , the solution of the problem of moving discs from needle A to needle C has
three types,
1. Move N-1 disc from A to B
2. Move discs from A to C
3. Move N-1 discs from B to C.
A close examination of the first and third steps will reveal that they are recursive in nature,
A General algorithm for solving the tower of Hanoi problem is now given,
i) Push parameters and return address on Stack.
ii) If the stopping value has been reached then pop the stack to return to previous
level else move all expect the final disc from starting to intermediate needle.
iii) Move final disc from start to destination needle .
iv) Move remaining discs from intermediately to destination needle.
v) Return to previous level by popping stack.
ALGORITHM
1. [SAVE PARAMETER AND RETURN ADDRESS]
CALL PUSH (ST,TOP,TEMP-REC)
THE EFFECT OF THE PUSH OPERATION IS AS FOLLOWS
TOPTOP+1,N[TOP]N-VALUE,SN[TOP]SN-VALUE,IN[TOP]IN-
VALUE,DN[TOP]DN-VALUE,RETADDR[TOP]ADDRESS)
2. [TEST FOR STOPPING VALUE OF N, IF NOT REACHED MOVE N-1 DISCS FROM
START NEEDLE TO INTERMEDIATE NEEDLE]
IF N[TOP]=0
THEN GO TO RET-ADDR[TOP]
ELSE
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 23
N-VALUE N[TOP]-1
SN-VALUESN[TOP]
IN-VALUEDN[TOP]
DN-VALUEIN[TOP]
ADDRESSSTEP 3
GO TO STEP 1
3. [MOVE N TH DISC FROM START TO DESTINATION NEEDLE MOVE N-1 DISCS
FROM INTERMEDIATE TO DESTINATION NEEDLE]
TEMP-RECPOP(ST,TOP)
WRITE (‘DISC’,N,’FROM NEEDLE’,SN,’TO NEEDLE,DN)
N-VALUEN[TOP]
SN-VALUEIN[TOP]
IN-VALUESN[TOP]
DIAGRAM REPRESENTATION
LEVEL NO DESCRIPTION STACK CONTAINS
1. STEP1:PUSH[ST,0(2,A,B,C,MAINADDS)
STEP2: IF N≠0
N-VALUEN[TOP]-1
SN-VALUESN[TOP] A
IN-VALUEDN[TOP] C
DN-VALUEIN[TOP] B
RET-ADDRESS STEP 3
GO TO STEP 1
TOP AC
2. STEP 1:PUSH[ST,1(1,A,C,B,STEP 3)]
STEP 2:IF N≠0
N-VALUEN[TOP]-1
SN-VALUESN[TOP] A
IN-VALUEDN[TOP] B
DN-VALUEIN[TOP] C
RET-ADDRESS STEP 3
GO TO STEP 1 TOP AB
N 2
SN A
IN B
DN C
RE Main
address
2 1
A A
B C
C B
Main
address
STEP 3
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 24
3. STEP 1:PUSH[ST,2(0,A,B,C,STEP3)]
STEP 2: IF N=0
POP(ST,TOP)
N-VALUEN[TOP]-1
SN-VALUEIN[TOP] B
IN-VALUESN[TOP] A
DN-VALUEDN[TOP] C
RET-ADDRESS[TOP] TOP AC
4. POP(ST,TOP)
WRITE(DISC 1 A TO B)
N-VALUEN[TOP]-1=0
SN-VALUEIN[TOP] C
IN-VALUESN[TOP] A
DN-VALUEDN[TOP] B
RET-ADDRESSSTEP 4
TOP CB
STEP 4: POP(ST,TOP)3
2(ST,TOP)
GO TO RET-ADDR
WRITE (DISC 2 FROM A TO C)
N-VALUE2-1
SN-VALUEB
IN-VALUEA
DN-VALUEC
ADDRESSSTEP 4
GO TO STEP 1 TOP AC &BC
5. STEP 1:PUSH[ST,1(1,B,A,C,STEP 4)]
STEP 2:IF N≠0
N-VALUE1-1
SN-VALUEB
IN-VALUEC
DN-VALUEA
ADDRESSST3P 3
GO TO STEP 1
STEP 3: DN-VALUEDN[TOP] TOP BA
ADDRESSSTEP 4
GO TO STEP 4
2 1 0
A A A
B C B
C B C
Main
address
Step
3
Step3
2 1 0
A A C
B B A
C C B
Main
address
Step
3
Step4
N 2 1
SN A B
IN B A
DN C C
RE Main
address
Step
4
2 1 0
A B B
B A C
C C A
Main
address
STEP 3 STEP
3
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 25
STEP 4: [RETURN TO PREVIOUS LEVEL]
TEMP-RECPOP(ST,TOP)
GO TO REC-ADDR
3.INFIX, POSTFIX AND PREFIX NOTATIONS
Every expression can be denoted in 3 types and they are
i) Infix Notation
ii) Postfix or polish or reverse polish notation
iii) Prefix notation
INFIX
The expressions which are in normal format is known as infix notation. In this type the
operation lies between the two variables.
Ex: A+B
PREFIX
In prefix notation the operator comes first followed by two operands.
Ex:+AB
POSTFIX
In Postfix notation the operands comes first followed by the operator
Ex: AB+
ALGORITHM : REVERSE POLISH
REV-POL Given an input string infix containing an infix expression which has been P
added on the right with ‘(‘ and whose symbols have precedence values given by tables, a vector
‘S’ used as a stack and function ‘NEXTCHAR’ which when invoked returns the next character
of its arguments, this algorithm converts INFIX TO REVERSE POLISH and places the results in
string polish.
The integer variable Top denotes the top of the stack algorithm. PUSH & POP are used
for stack manipulation. The integer variables rank accumulates the rank of the expression.
Finally, the string variable TEMP is used for temporary storage purpose.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 26
1. [Initialize stack]
Top 1
S[TOP]’(‘
2. [INITIALIZE OUTPUT STRING AND RANK COUNT]
POLISH”0” OR ” “
RANK0
3. [GET 1ST
INPUT SYMBOL]
NEXTNEXT CHAR (INFIX)
4. [TRANSLATE THE INFIX EXPRESSION]
REPEAT THROUGH STEP-7 WHILE NEXT ≠” “
5. [REMOVE SYMBOLS WITH GREATE PRECEDENCE FROM STACK]
IF TOP< 1 THEN
WRITE (‘INVALID’)
EXIT
REPEAT WHILE F(NEXT)<G(S[TOP])
TEMPPOP(S,TOP)
POLISHPOLISH ‘0’ TEMP
RANK<-RANK + R[TEMP]
IF RANK< 1 THEN
WRITE (‘INVALID’)
EXIT
6. [ARE THERE MATCHING PARANTHESIS]
IF F(NEXT) ≠G (S[TOP]) THEN
CALL PUSH (S,TOP,NEXT)
ELSE POP (S,TOP)
7. [GET NEXT INPUT SYMBOL]
NEXTNEXT CHAR(INFIX)
IF TOP≠0 OR RANK≠1 THEN
WRITE (‘INVALID’)
ELSE WRITE(‘VALID’)
EXIT
A trace of the stack contents and the polish string ‘POLISH’ for the infix expression.
Q=A+(B*C-(D/E^/F)*G)*H
P=ABC*DEF^/G*-H*+
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 27
PRECEDENCE TABLE
SYMBOL INPUT PRECEDENCE
FUNCTION OF F
STACK PRECEDENCE
FUNCTIONING G
RANK
FUNCTION
R
+,- 1 2 -1
*,/ 3 4 -1
6 5 -1
Variable 7 8 1
( 9 0 -
) 0 - -
SYMBOL SCANNED STACK EXPRESSION P
(
A ( A
+ (+ A
( (+( A
B (+(* AB
* (+(* AB
C (+( ABC
- (+(- ABC*
( (+(-( ABC*
D (+(-( ABC*D
/ (+(-(/ ABC*D
E (+(-(/ ABC*DE
^ (+(-(/^ ABC*DE
F (+(-(/^ ABC*DEF
) (+(- ABC*DEF^/
* (+(-* ABC*DEF^/
G (+(-* ABC*DEF^/G
) (+ ABC*DEF^/G*-
* (+* ABC*DEF^/G*-
H (+* ABC*DEF^/G*-H
) ABC*DEF^/G*-H*+
QUEUES
Another important subclass of lists permits deletion to be performed at one end of a list
and insertion at the other. The information in such as list is processed in the same order as it was
received that is on a FIRST IN FIRST OUT (FIFO)Or a FIRST COME FIRST SERVED(FCFS)
basis. This type of list is frequently referred to as a queue.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 28
Following figure is a representation of a queue illustrating how an insertion is made to
the right of the most element in the queue and how a deletion consists of deleting the left most
element in the queue.
REPRESENTATION OF QUEUE
FRONT REAR
INSERTION
DELETION
The familiar and traditional chain of a queue in a check outline at a super mark cash
register. The first person in line is usually the first to be checked out.
A final example of a queue is the line of cars waiting to proceed in some fixed direction at
an insertion of streets. The deletion of a car corresponds to the first car in the line passing
through the intersection, while an insertion to the queue consists waiting the end of the line of
existing cars waiting to proceed through the intersection.
PROCEDURE QUEUE INSERT(Q,F,R,N,Y)
Given F and R pointers to the front and rear elements of a queue ,a queue consisting of N
elements and y elements, this procedure inserts Y at the rear of a Queue. Prior to the first
invocation of the procedure F and R have been set to Zero.
1. [OVERFLOW]
IF R>=N
THEN WRITE (‘OVER FLOW’)
RETURN
2. [INCREMENT REAR POINTER]
RR+1
3. [INSERT ELEMENT]
Q [R]Y
4. [IS FRONT POINTER PROPERLY SET?]
IF F=0
THEN F1
RETURN
The following algorithm deletes an elements from a queue.
FUNCTION Q DELETE(Q,F,R)
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 29
Given F and R the pointers to the front and rear elements of a queue respectively and the queue
Q to which they correspond this function deletes and returns the last elements of the queue y is a
temporary variable.
1.[UNDERFLOW]
IF F=O THEN WRITE (‘UNDERFLOW’)
RETURN(O)
0DENOTES AN EMPTY QUEUE
2. [DELETE ELEMENTS]
YQ[F] (Y IS ITEM)
3. [QUEUE EMPTY]
IF F=R THEN FR0
ELSE
FF+1 (INCREMENT FRONT POINTER)
4. [RETURN ELEMENT]
RETURN [Y]
CIRCULAR QUEUE
Circular queue are the ones implemented in circular from rather than a straight line. Circular
queues overcome the problem of unutilized space in the linear queues. The circular queue
considers at opposite end, that is why, if the space is there in the beginning , the rear shifts back
to beginning after reaching the max, possible storage.
REAR
FRONT
PROCEDURE FOR INSERTION
1. [RESET REAR POINTER]
IF R=N THEN R1
ELSE RR+1
2. [OVERFLOW]
IF F=R THEN WRITE[‘OVERFLOW’]
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 30
RETURN
3. [INSERT ELEMENT]
Q[R]Y
4. [IF FRONT POINTER PROPERLY SET]
IF F=0 THEN F1
RETURN
PROCEDURE FOR DELETION
1. [UNDERFLOW]
IF F=0 THEN WRITE (‘UNDERFLOW’)
RETURN (0)
2. [DELETE ELEMENT]
YQ[F]
3. [QUEUE EMPTY]
IF F=R THEN FR0
RETURN [Y]
DEQUEUE
DEQUEUE (DOUBLE ENDED QUEUE) is a linear list in which insertion and deletion are
made to or from either end of the structure. Such a structure can be represented by the following
diagram.
DELETION INSERTION
DELETION
REAR
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 31
INSERTION FRONT
It is clear that a dequeue is more general than a stack or a queue.
There are two variation of a dequeue namely
1. The input restricted dequeue
2. The output restricted dequeue.
The input restricted dequeue allows insertion at only one end, while an output restricted dequeue
permits deletions from only one end.
PRIORITY : Q
Adding and Deleting is according to the priority.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 32
UNIT III
LINKED LISTS
DEFINITION
A list has been defined to consists of an ordered set of elements which may vary in number.
A simple way to represent a linear list in to expand each mode to contain a link or pointer to the
next node. This representation is called a one way chain or singly linked list and it can displayed
simply as shown below.
A)
  ……… 
B)
  
2000 2010 2002 2012
C) INSERT NODE X
 
2000 2010 2002 2012
2100
D) DELETE NODE C
  
2000 2010 2002 2012
A 2010 B 2002 C 2012 E
A 2100 B 2002 C 2012 E
X 2010
A 2010 B 2012 E
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 33
In figure (A) the variable first contains the address or pointer which gives the location of the
first node of the list. Each node is divided in to two parts. The first part represent the information
of the element and the second part contains the address of the next node. The last node of the list
does not have a successor node and consequently no actual address is stored in the pointer field.
In such case, a null value is stored as address. For Example, the linked list in fig(B) represents a
4 nodes units whose elements are located in memory locations 2000,2010,2002 and 2012
respectively . The linked address of NULL in the last node signals the end of the list.
OPERATIONS
1. INSERTION
2. DELETION
An insertion is performed in a straight forward manner. If a new element is to be
inserted following the first element, this can be accomplished by merely interchanging
pointers.
For example, this can be shown in fig(C) for a 4 th element.
The deletion of the fourth element from the original list can be performed by using the
pointer change as shown in figure(D). It is clear that the insertion and deletion operations are
more efficient when performed on linked list than an sequentially allocated list.
OPERATIONS ON LINEAR LIST USING SINGLY LINKED LIST STORAGE
A typical element or node consists of two fields namely an information field called
INFO and a pointer field denoted by LINK. The name of a typical element is denoted by
NODE.
Pictorially , the NODE structure is as follows
INFO LINK
NODE
It is further assumed that an available area of storage for this node structure consists of a
linked state of available nodes as shown in Fig(A).
TYPES OF LINKED LIST
1. INTERNAL ADDRESS
2. EXTERNAL ADDRESS
3. NULL ADDRESS
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 34
FUNCTION INSERT (X,FIRST)
Given X, a new element and first a pointer to the first element of a linked linear list whose
typical node contains INFO & LINK field as previously discussed. This function inserts X.
AVAIL is a pointer to the top element of the availability stack. NEW is a temporary pointer
variable. It is required that X proceed the node whose address is given by FIRST.
1. [UNDERFLOW]
IF AVAIL= NULL THEN WRITE (AVAILIABILITY STACK UNDERFLOW)
RETURN[FIRST]
2. [OBTAIN ADDRESS OF NEXT FREE NODE]
NEW AVAIL
3. [REMOVE FREE NODE FROM AVAILIABILITY STACK]
AVAIL LINK(AVAIL)
4. [INITIALIZE FIELDS OF NEW NODE AND ITS LINK TO LIST]
INFO(NEW) X
LINK(NEW)FIRST
5. [RETURN ADDRESS OF NEW NODE]
RETURN (NEW)
FUNCTION INSERT END (X, FIRST)
1. [UNDERFLOW]
IF AVAIL=NULL THEN WRITE (AVILABILITY STACK UNDERFLOW)
RETURN (FIRST)
2. [OBTAIN ADDRESS OF NEXT FREE NODE]
NEW AVAIL
3. [REMOVE FREE NODE FROM AVAILABILITY STACK]
AVAILLINK(AVAIL)
4. [INITIALIZE FIELDS OF NEW NODE]
INFO(NEW)X
LINK(NEW)NULL
5. [IS THE LIST EMPTY]
IF FIRST =NULL THEN RETURN (NEW)
6. [INITIATE SEARCH FOR LAST NODE]
SAVE FIRST
7. [SEARCH FOR END OF LIST]
REPEAT WHILE LINK(SAVE)≠ NULL
SAVE LINK(SAVE)
8. [SET LINK FIELD OF LIST NODEE TO END]
LINK(SAVE)NEW
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 35
9. [RETURN FIRST NODE POINTER]
RETURN (FIRST)
DELETING A NODE
FUNCTION DELETE(X,FIRST)
1. [EMPTY LIST]
IF FIRST= NULL THEN WRITE (UNDERFLOW)
RETURN
2. [INITIALIZS SEARCH FOR X]
TEMP FIRST
3. [FIND X]
REPEAT THROUGH STEP-5 WHILE
TEMP≠ X AND LINK(TEMP) ≠ NULL
4. [UPDATE PREDECESSOR MARKER]
PRED TEMP
5. [MOVE TO NEXT NODE]
TEMPLINK[TEMP]
6. [END OF THE LIST]
IF TEMP ≠ X THEN WRITE(NODE NOT FOUND)
RETURN
7. [DELETE X]
IF X= FIRST [IS X THE FIRST NODE] THEN
FIRST<LINK(FIRST)
ELSE LINK(PRED)LINK(X)
8. [RETURN NODE TO AVAILABILITY AREA]
LINK(X)AVAIL
AVAILX
RETURN
COPY A NODE
A General algorithm to copy a linked list is now presented.
1. [EMPTY LIST]
IF FIRST=NULL THEN RETURN [NULL]
2. [COPY FIRST NODE]
IF AVAIL =NULL THEN WRITE (AVAILABILITY STACK UNDERFLOW)
RETURN (0)
ELSE
NEWAVAIL
AVAILLINK(AVAIL)
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 36
FIELDINFO(FIRST)
BEGINNEW
3. [INITIALIZE TRAVERSAL]
SAVEFIRST
4. [MOVE TO NEXT NODE IF NO AT THE END OF LIST]
REPEAT THROUGH STEP-6 WHILE LINK[SAVE] ≠NULL
5. [UPDATE PREDECESSOR AND SAVE POINTERS]
PREDNEW
SAVELINK(SAVE)
6. [COPY NODE]
IF AVAIL= NULL THEN WRITE(AVAILABILITY STACK UNDERFLOW)
RETURN (0)
ELSE
NEWAVAIL
AVAILLINK(AVAIL)
FIELD(NEW)INFO(SAVE)
PTR(PRED)NEW
7. [SET LINK OF LAST NODE AND RETURN]
PTR(NEW)NULL
RETURN(BEGIN)
POLYNOMIAL
A node consists of number of fields each of which can represent an int , a real number
etc..except for one field called the pointer which contains the location of the next node in the list.
Consider the example of representing a term of a polynomial in the variables x,y,z a
typical node is represented as follows.
Power-x Power-y Power-z Co-efficien LINK
TERM
Which consists of 5 sequentially allocated fields, that we collectively refer to ‘TERM’. The
first three fields represent the power of the variables x,y and z respectively. The 4 th and 5 th
field represent the co efficient of the ‘TERM’ in the polynomial and the address of the next in the
polynomial respectively.
For example the term 3xy would be represented in the figure,
1 1 0 3
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 37
This selection of a particular field with in a node for a polynomial example in an easy
matter.Our algorithm notation allows the referring of any field of a node given the pointer p to
the node.
Co-eff(p) denotes the coefficient field of the node pointed to by P. similarly the exponent of
x,y,z are given by power x(p),power y(p) and power z(p) respectively and the pointer to the next
node is given by LINK(P).
Consider as an ex, the representation of the polynomial 2x2
+5xy+y2
+yz as a linked list.
Assuming that the nodes in the list are to be stored such the term pointer to by p, proceeds
another term indicated by Q, if power x(P) is greater than power x(Q) or if the powers of x are
equal, then power y(p) ,must be equal than power y(Q) or if the power of y are equal then power
z(p) must be greater than power z(Q).
For example, the list is represented by the following figure,( 2x2
+5xy+y2
+yz)
X y z co-eff
2 0 0 2
2x2
1 1 0 5
5xy
0 2 0 1
Y2
0 1 1 1
Yz
OPERATION ON POLYNOMIAL
INSERTION
FUNCTION POLY FRONT (NX,NY,NZ,NCOEFF,POLY)
Given the definition of the node structure TERM under availability area from which we can
obtain such nodes, it is required to insert a node in the linked list so that it immediately preceeds
the node whose address is designated by the pointer POLY. The fields of the new term are
denoted by NX,NY,NZ,NCOEFF which corresponds to the exponents for x,y,z and the co-
efficient value of the term respectively, NEW is a pointer variable which contains the address of
the new node.
1. [OBTAIN A NODE FROM AVAILABLE STORAGE]
NEWTERM
2. [INITIALIZE NUMERIC FIELDS]
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 38
POWER-X (NEW)NX
POWER-Y(NEW)NY
POWER-Z(NEW)NZ
COEFF(NEW)NCOEFF
3. [SET LINK TO THE LIST]
LINK[NEW]POLY
4. [RETURN FIRST NODE POINTER]
RETURN [NEW]
EXAMPLE :YZ+Y2
+5XY+2X2
1. POLY
0 1 1 1
2. POLY
0 2 0 1
0 1 1 1
3. POLY
1 1 0 5
0 2 0 1
0 1 1 1 -
4. POLY
2 0 0 2
1 1 0 5
0 2 0 1
0 1 1 1 -
FUNCTION POLYEND (NX,NY,NZ,N,COEFF,POLY)
Given the definition of the node structure TERM under availability area from which we can
obtain such node is referred to insert a node in the , list so that it immediately proceeds the node
whose address is designated by the pointer POLY. The fields of the new TERM are denoted by
NX,NY,NZ,NCOEFF Which corresponds to the exponents for x,y,z and the co efficient value of
the term respectively. NEW is a pointer variable which contains the address of new node. SAVE
is a temporary pointer variable.
1. [OBTAIN A NODE FROM AVALIABLE STORAGE]
NEW TERM
2. [INITIALIZE NUMERIC FIELDS]
POWER X(NEW)NX
POWER Y(NEW)NY
POWER Z(NEW)NZ
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 39
3. [IS THE LIST EMPTY]
IF POLY=NULL THEN RETURN[NEW]
4. [INITIATE SEARCH FOR LAST NODE]
SAVEPOLY
5. [SEARCH FOR END OF LIST]
REPEAT WHILE LINK(SAVE) ≠ NULL
SAVELINK(SAVE)
6. [SET LINK FIELD OF LAST NODE TO NEW]
LINK(SAVE)NEW
7. [RETURN FIRST NODE POINTER]
8. RETURN(POLY)
EXAMPLE :2X2
+5XY+Y+YZ
1. POLY
2 0 0 2
2. POLY
2 0 0 2
1 1 0 5
3. POLY
2 0 0 2
1 1 0 5
0 2 0 1 -
4. POLY
2 0 0 2
1 1 0 5
0 2 0 1
0 1 1 1 -
POLYLAST(NX,NY,NZ,NCOEFF,POLY)
Given the definition of the node structure TERM under availability area from which we can
obtain such nodes, it is required to insert a node in a linked list. So that it immediately proceeds
the node whose address is designated by the pointer POLY.
The global pointer variable LAST denotes the address of the last node in the list. The fields of
the new term are denoted by NX,NY,NZ,NCOEFF, which corresponds to the term respectively
NEW is a pointer variable which contains the address of the new node.
1. [OBTAIN A NODE FROM AVAILABLE STORAGE]
NEWTERM
2. [INITIALIZE NUMERIC FIELDS]
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 40
POWER X(NEW)NX
POWER Y(NEW)NY
POWER Z(NEW)NZ
CO-EFF(NEW)NCOEFF
LINK(NEW)NULL
3. [IS THE LIST EMPTY]
IF POLY = NULL THEN LASTNEW
RETURN(NEW)
4. [INSERT NODE IN NON EMPTY LIST]
LINK(LAST)NEW
LASTNEW
POLYNOMIAL ADDTION
A general algorithm for adding two polynomial is presented.
FUNCTION POLY ADD(P,Q)
Given two polynomial whose first terms are referred by pointer variables P & Q respectively,
and insertion function as described in function copy, is required to add their polynomials and
score their sum in a third polynomial which is referenced by the pointer variable R. The original
polynomials are to remain unchanged. PSAVE & QSAVE are pointer variables.
A1,A2,B1,B2,C1,C2,D1 & D2 are temporary variables of global variables.
1. [INITIALIZE]
RNULL
PSAVEP
QSAVEQ
2. [END OF ANY POLYNOMIAL]
REPEAT THROUGH STEP4 WHILE P ≠ NULL AND Q ≠ NULL
3. [GET VALUES FOR EACH THEM]
A1POWER X(P)
A2POWER X(Q)
B1POWER Y(P)
B2POWER Y(Q)
C1POWER Z(P)
C2POWER Z(Q)
D1 COEFF(P)
D2COEFF(Q)
4. [COMPARE TERMS]
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 41
IF (A1=A2)AND(B1=B2)AND(C1=C2) THEN
IF D1+D2 ≠0 THEN
RPOLYLAST(A1,B1,C1,D1+D2,R)
PLINK(P)
QLINK(Q)
ELSEIF[(A1>A2)OR(A1=A2)AND(B1>B2)] OR[(A1=A2)AND(B1=B2)AND(C1>C2)]
THEN RPOLYLAST(A2,B2,C1,D1,R)
PLINK(P)
ELSE
RPOLYLAST(A2,B2,C2,D2,R)
QLINK(Q)
5. [NOT AT END OF ONE OF THE POLYNOMIAL]
IF P ≠ NULL THEN LINK(LAST)COPY(P)
ELSE IF Q≠NULL THEN LINK(LAST)COPY(Q)
6. [RESTORE INITIAL POINTER VALUES FOR P & Q]
PPSAVE
QQSAVE
7. [RETURN POINTER TO SUM POLYNOMIAL]
RETURN(R)
DOUBLY LINKED LINEAR LIST
Linked linear list implies that each node must contain two link fields instead of the usual
one. The links are used to denote the predecessor and successor of a node. The link denoting the
predecessor of a node is called the left link containing this type of node is called doubly linked
linear list or a two way chain.
L R
Where L and R are pointer variables denoting the left most and right most nodes in the list
respectively. The left link of the leftmost and the right link of the rightmost node are both NULL,
indicating the end of the list for each direction. The left and right link of a node are denoted by
the variables LPTR and RPTR respectively.
PROCEDURE FOR DOUB INS(L,R,M,X)
Given a doubly linked linear list whose leftmost and rightmost node address are given by the
pointer variable L and R respectively. It is required to insert a node whose address is given by
pointer variable P. The right and left link of node are denoted by LPTR and RPTR. The
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 42
information field of a node denoted by the variable M. The information is to entered in the node
is contained in X.
CREATION OF LINK
1. PROCEDURE DOUBLE INSERT (L,R,M,X)
2. GETNODE (P)
3. INFO(P)X
4. IF R=NULL THEN LPTR(P)RPTR(P)NULL
5. RETURN
INSERTION OF FIRST NODE
1. GETNODE(P)
2. INFO (P)X
3. IF M=L THEN
LPTR (P)NULL
RPTR(P)M
LPTR(M)P
RETURN
INSERTION TO MIDDLE
1. GETNODE (P)
2. INFO(P)
3. LPTR(P)LPTR(M)
4. RPTR(P)M
5. LPTR(M)P
INSERTION TO LAST NODE
1. GETNODE(P)
2. INFO(P)X
3. RPTR(M)P
4. LPTR(P)M
5. RPTR(P)NULL
LPTR INFO RPTR LPTR INFO RPTR LPTR INFO
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 43
PROCEDURE DOUB DEL(L,R,OLD)
Given a doubly linked list, get the address of the leftmost and right most nodes given by the
pointer variable L &R respectively. It is required to delete the node whose address is containedin
the variable OLD. Nodes contain left and right links with names LPTR and RPTR respectively.
PROCEDURE DOUB DEL(L,R,OLD)
1. UNDERFLOW
IF R=NULL THEN WRITE(UNDERFLOW)
RETURN
2. DELETE NODE (ONE NODE,L,R)
IF L=R THEN
LRNULL
RETURN
3. DELETE NODE(FIRST NODE]
IF OLD=L THEN LRPTR(L)
LPTRNULL (OR)RETURN(OLD)
FREENODE(OLD)
4. LAST NODE
IF OLD=R THEN
RLPTR (R)
RPTR (R )NULL
FREENODE(OLD)
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 44
UNIT-IV
GRAPHS
DEFINITION OF GRAPH
A graph G consist of a non-empty set V called the set of nodes(points, vertices) of the graph, a
set E which is the set of edges of the graph and a mapping from the set of edges to a set of pair of
elements of v. A Graph defined as G=(V,E).
V2
E1 E2
V1 V3
E4 E3
V4
In this V1,V2,V3,V4 are set of nodes and E1,E2,E3,E4 are set of edges.
ADJACENT NODE
Any two nodes which are connected by an edge in a graph are called adjacent node.
V1 E V2
V1 and V2 are adjacent node which are connected by an edge E in a graph.
DIRECTED EDGE
Graph G is equal to (V,E) an edge which is directed from one node to another is called a directed
Edge.
V1 E V2
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 45
UNDIRECTED EDGE
An edge which has no specific direction is called an undirected edge.
V1 E V2
There is an no specific direction. So it is undirected graph.
TYPE OF GRAPHS
DIRECTED GRAPH
A Graph In Which Every Edge Is Directed is called a directed graph (or) Dia graph (or) Di
graph.
V2
E1 E2
V1 V3
E4 E3
V4
UNDIRECTED GRAPH
A Graph in which every edge is undirected is called an undirected graph.
V2
E1 E2
V1 V3
E4 E3
V4
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 46
MIXED GRAPH
Some of the edges are directed and some of the edges are undirected in a graph, then the graph
is a mixed graph.
V2
E1 E2
V1 V3
E4 E3
V4
INITIATING AND TERMINATING
Pair of node (U,V) then the edge x is said to be initiating is the node U and terminating Or
ending is the node V. The nodes U and V are also called the initial and terminal nodes of the
edge x.
U V
LOOP
An edge of a graph, which join a node itself is called a loop.
V2
E1 E2
V1 V3
E4 E3
V4
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 47
PARALLEL GRAPH
Certain pair of nodes joined by more than one edge, such edges are called parallel graph.
V2
E1 E2
V1 V3
E4 E3
V4
MULTI GRAPH
Any graph which contain some parallel edges is called a multi graph.
V2
E1 E2
V1 V3
E4 E3
V4
SIMPLE GRAPH
No more than one directed edge in the case of a directed graph such a graph is called a
simple graph.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 48
WEIGHTED GRAPH
A Graph in which weights are assigned to every edge is called a weighted graph.
5 20
10
V3
30 40
ISOLATED GRAPH
A node which is not adjacent to any other node is called an isolated node
2
1 5
6 6
3 4
HERE 6 IS AN ISOLATED GRAPH
NULL GRAPH
A Graph containing only isolated nodes is called a null graph.
V2
V1 V3
V4
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 49
IN DEGREE, OUT DEGREE AND TOTAL DEGREE
In a directed graph for any node, the number of edges which have U as their initial node is
called the Out Degree of the nodes. The number of edges which have V as their terminal node is
called IN DEGREE of V and the sum of the out degree and in degree of a node is called TOTAL
DEGREE.
EXAMPLE 1:
1
3 2
IN DEGREE=1 , OUT DEGREE=2, TOTAL DEGREE=3
EXAMPLE 2:
Here e2 and e4 are the out degree, e1 is the in degree.
PATH
A Path is said to traverse through the nodes appearing in the sequence, originating in the
initial node of the first edge and ending in the terminal node of the last edge in the sequence.
V1 V2
V4 V3
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 50
V1V2V3V4
V1V2V4
V1V3V4
V1V4
LENGTH
The number of edges appearing in the sequence of a path is called the length of the path.
V1 V2
V4 V3
V1V2V3V4 =3
V1V2V4 =2
V1V3V4 =2
V1V4 =1
CYCLIC
A path which originate and ends in the same node is called a cyclic.
ACYCLIC
A Simple diagraph which does not have any cyclic is called Acyclic.
DIRECTED TREE
A Directed tree is an acyclic diagraph which has one node called its root. An isolated
node is called a directed tree. In a directed tree any node which has out degree 0 is called a
terminal node or leaf. An other node are called branch node.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 51
STRONGLY CONNECTED GRAPH
A Diagraph is called strongly connected if there is a directed path from any vertex to any
other vertex.
WEEKLY CONNECTED GRAPH
There does not exist a directed path from vertex, one to vertex 4, also from vertex 5 to
other vertex. It is called a weekly connected graph.
A special type of graph is called tree. A graph is a tree if it has two properties.
1. It is connected
2. There are no cycles in a graph.
EXAMPLES
1
2
3
4 5
A
B
C
D
1
2
3
4 5
1
2 3
4 5 6 7
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 52
GRAPH REPRESENTATION
Two such representations are commonly used there are,
1. Adjacent matrix
2. Adjacent list representation
The choice of representation depends on the application and function to be performed
on the graph.
ADJACENT MATRIX
A Adjacent matrix A for a graph g=(V,E) with n vertices, is an n cross n matrix of bits,
Such that A(i,j)=1, iff there is no such edge.
The figure shows the adjacent matrix the graph shown in figure.
The total number of 1’s accounts for the number of edges in the diagraph. The
number of 1’s in each row tells the out degree of corresponding vertex.
The adjacent matrix is a simple way to represent a graph but it has two disadvantages.
1. It take1s O(n2
) space to represent a graph with n vertices even for sparse graph and
2. It takes (n2
) time to save most of the graph problems.
Vertex 1 2 3 4 5
1 0 1 1 0 0
2 0 0 1 0 0
3 0 0 0 1 0
4 0 0 0 0 0
5 1 0 1 1 0
1
5
4
3
2
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 53
ADJACENCY LIST REPRESENTAION
In this representation we score a graph as a linked structure, We score all the vertices
in a list and then for each vertex, we have a linked list of its adjacent vertices.
EXAMPLE
V6
V5
V4
V2
V3
V1
V1 V1
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 54
UNIT – V
TREES
DEFINITION OF TREE
Usually, draw trees with a root at the top. Each node has exactly one node about it which is
called its parent. A node directly below a node is called a children.
TREE RELATED TERMS
A Tree is a non-empty collection of vertices and edges that satisfy certain requirements.
A vertex is a simple object (node) that can have a name and carry other associated
information. An edge is a connection between two vertices. A tree may, therefore, be defined as
a finite set of one or more vertices such that,
1. There is a one specially designated vertex called root.
2. The remaining vertices are partitioned in to collection of subtree, with each of which is
also a tree.
FOREST TREE
A Set of trees is called a forest tree.
EXAMPLE
A
B C D
G
F
E
H I J
K L M
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 55
PROPERTIES OF A TREE
1. Any node can be root of the tree and each node in the tree has the property that there is
exactly one path connecting that node with every other node in the tree.
2. Each node, except the root has a unique parent and every edge connects a node to its
parent. A tree worth N nodes has N-1 edges.
BINARY TREES
A Binary tree is a tree which is either empty or consists of a root node and two disjoint
binary trees called left sub tree and right sub tree. In figure a binary tree is depicted with a left
sub tree L(T) and the right sub tree is denoted by R(T).In a binary tree no node can have more
than two children, or two node.
PROPERTIES OF BINARY TREE
1. A Binary tree with N internal node have maximum of N+1 external node. Root is
considered as an external node.
2. The external path, length of any binary tree with a internal node is 2n
>the internal path
length.
3. The height of full binary tree with N internal node is above log2 N.
FULL BINARY TREE
A Full binary tree or a complete binary tree is a binary tree in which all internal nodes have
degree and all leaves are at the same level.
EXAMPLE
LEVEL 1
LEVEL2
LEVEL3
1
2 3
4 5 6 7
1
2 3
4 5 6 7
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 56
TREE REPRESENTATION
1. VENN DIAGRAM
2. NESTING PARANTHESIS
3. TEBLE OF CONTENTS
4. LEVEL NUMBER FORMAT
EXAMPLE
VENN DIAGRAM
NESTING PARANTHESIS
(V0(V7(V8)(V9(V10)))(V1(V2(V5)(V6))(V3)(V4)))
V0
V1
V7
V3
V9
V8 V4
V10 V5
V2
V6
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 57
TABLE OF CONTENTS
VO --------------------------------------------
V1--------------------------------------------
V2-----------------------------------------
V5-------------------------------------
V6-----------------------------------
V3-------------------------------------------
V4--------------------------------------------
V7----------------------------------------------
V8------------------------------------------
V9-------------------------------------------
V10---------------------------------------
LEVEL NUMBER FORMAT
1. VO --------------------------------------------
2. V1--------------------------------------------
3. V2-----------------------------------------
4. V5-------------------------------------
4. V6-----------------------------------
3. V3-------------------------------------------
3. V4--------------------------------------------
2. V7----------------------------------------------
3. V8------------------------------------------
3. V9-------------------------------------------
4. V10---------------------------------------
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 58
CONVERSION OF BINARY TREE
A forest tree can also be represented by a binary tree. The two stages to obtain a binary
tree which represents a given ordered tree is as follows. As a first step, we delete all the left most
branch. Also we draw edges from a node to the node on the immediate right, if any, which is
situated at the same level.
Once this is done, then for any particular node we choose its left and right children in the
following manner. The left child is the node and the right child is the node to the immediate right
of the given node on the same horizontal line. Such a binary tree will not have a right subtree.
GENERAL TREE TO BINARY TREE
GIVEN DIRECTED TREE
STAGE 1
a
b f
c d g j k
e h i
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 59
STAGE 2
FOREST TO BINARY TREE
STAGE 1
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 60
STAGE 2
OPERATION S ON BINARY TREE [TREE TRAVERSAL]
One of the most common operations performed on tree structure is that of traversal. This is a
procedure by which each node in the tree is processed exactly once in a systematic manner.
There are three main ways of traversing a binary tree.
1. PREORDER
2. INORDER
3. POSTORDER
The preorder traversal of a binary tree is defined as follows,
1. Process the root node
2. Traverse the left subtree in preorder
3. Traverse the right subtree in preorder
EXAMPLE
A
B D
C E G
F
ANS: ABCDEFG
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 61
The inorder traversal of a binary tree is given by the following steps,
1. Traverse the left subtree in preorder
2. Process the root node
3. Traverse the right subtree in preorder
EXAMPLE
A
B D
C E G
F
ANS: CBAEFDG
Finally, we define the post order traversal of a binary tree as follows,
1. Traverse the left subtree in preorder
2. Traverse the right subtree in preorder
3. Process the root node
EXAMPLE
A
B D
C E G
F
ANS: CBFEGDA
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 62
NON-RECURSIVE MANNER
PROCEDURE FOR PREORDER
1. [INITIALIZE]
IF T=NULL THEN WRITE(EMPTY TREE)
RETURN
ELSE
TOP0
CALL PUSH(S,TOP,T)
2. [PROCESS EACH STACKED BRANCH ADDRESS]
REPEAT STEP 3 WHILE TOP >0
3. [GET STORED ADDRESS AND BRANCH LEFT]
PPOP(S,TOP)
REPEAT WHILE P≠ NULL
WRITE (DATA(P))
IF RPTR(P) ≠NULL
THEN CALL PUSH(S,TOP,RPTR(P))
PLPTR(P)
4. [FINISHED]
RETURN
PROCEDURE FOR POST ORDER
1. [INITIALIZE]
IF T=NULL
THEN WRITE(EMPTY TREE)
RETURN
ELSE PT
TOP0
2. [TRAVERSA IN POSTORDER]
REPEAT THROUGH STEP 5 WHILE TRUE
3. [DESCEND LEFT]
REPEAT WHILE P≠NULL
CALL PUSH(S,TOP,P)
PLPTR(P)
4. [PROCESS A NODE WHOSE LEFT AND RIGHT SUBTREE HAVE BEEN
TRAVERSED]
REPEAT WHILE S[TOP]<0
PPOP(S,TOP)
WRITE(DATA(P))
IF TOP=0
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 63
THEN
RETURN
5. [BRANCH RIGHT AND THEN MARK NODE FROM WHICH WE BRANCHED]
PRPTR(S[TOP])
S[TOP]S[TOP]
RECURSIVELY MANNER
PROCEDURE FOR INORDER
1. [CHECK FOR EMPTY TREE]
IF T=NULL THEN WRITE(EMPTY TREE)
RETURN
2. [PROCESS THE LEFT SUBTREE]
IF LPTR(T) ≠NULL THEN
CALL POSTORDER(LPTR(T))
3. [PROCESS THE RIGHT SUB TREE]
IF RPTR(T) ≠NULL THEN
CALL POSTORDER(RPTR(T))
4. [PROCESS THE ROOT NODE]
WRITE(DATA(T))
5. [FINISHED]
RETURN
GRAPH TRAVERSAL
1. BFS: QUEUEBREADTH FIRST SEARCH
2. DFS:STACKDEPTH FIRST SEARCH
PROCEDURE BFS(INDEX,LINK,QUEUE)
REACHspecifies whether the node has been reached in the traversal and its initial value is
false.
NODE NO Identifies the node number
DATAcontain a information of control
DISTANCEIt is the variable which contains a distance from the start node.
LIST PTRIt is a pointer to a list of adjacent edge for the node.
DEST INContains the number of terminal nodes for this edge.
EDGEPPTRPoints to the next edge in the list.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 64
ALGORITHM
1. [INITIALIZE]
REACH[INDEX]TRUE
DIST[INDEX]0
CALL QINSERT(QUEUE,INDEX)
2. [REPEAT UNTILL ALL NODE HAVE BEEN EXAMINED]
REPEAT THROUGH STEP-5 WHILE QUEUE IS NOT EMPTY.
3. [REMOVE THE CURRENT NODE TO THE EXAMINE FROM THE QUEUE]
CALL QDELETE(QUEUE,INDEX)
4. [FIND ALL UNABLE NODES ADJACENT TO CURRENT NODE]
LINKLIST PTR(INDEX)
REPEAT STEP-5 WHILE LINK ≠ NULL
5. [IS THIS A UNVISITED NODE LABEL IT AND ADDING IT IN A QUEUE]
IF NOT REACHED[DEST IN[LINK]] THEN
REACH [DEST IN[LINK]]DIST[INDEX]
CALL QINSERT(QUEUE,DEST IN (LINK))
LINKEDGE PTR(LINK)
6. [FINISHED]
RETURN
NOTE
INDEXCurrent node being processed
LINKPoint to the edge being examined
QUEUEDenote the name of the QUEUE
DIAGRAM REPRESENTATION
200 Mumbai
1300
Chennai 900 780
Delhi
Hyderabad
1400 600
160 Luck now
800 Calcutta
Bangalore
1
2
5 4
3
7
6
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 65
REACH NODE DATA DIST LINK(P) DEST IN EDGE PTR
True 1 Chennai 0 2 6
True 2 Bombay 200 5 4
True 3 Delhi 600 2 7
True 4 Hyderabad 780 7 5
True 5 Luck now 900 4 1
True 6 Bangalore 160 7 1
True 7 Calcutta 800 6 3
DEPTH FIRST SEARCH
PROCEDURE DFS(INDEX,COUNT)
Given the structure as described before, this recursive procedure calculates the depth first
search numbers for a graph. INDEX is the current index into the node table directory table and is
assumed to be initialized to one outside the procedure COUNT is used to keep track of the
current DFN node number and is initially set to zero outside the procedure. Finally, it is assumed
the DFN field as initialized to zero when the adjacency list structure was created.
ALGORITHM
1. [UPDATE THE DEPTH FIRST SEARCH NUMBER SET AND MARK CURRENT
NODE]
COUNTCOUNT+1
DFS[INDEX[COUNT
REACH[INDEX]TRUE
2. [SETUP LOOP TO EXAMINE EACH NEIGHBOUR OF CURRENT NODE]
LINKLIST PTR[INDEX]
REPEAT STEP 3 WHILE LINK ≠ NULL
3. [IF NODE HAS NOT BEEN MARKED,LABEL IT AND MAKE RECURSION CALL]
IF NOT REACH[DESIGN (LINK)]
THEN CALL DFS(DESTIN(LINK), COUNT)
LINK EDGE PTR(LINK)
4. [RETURN TO POINT OF CALL]
RETURN
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 66
DIAGRAM REPRESENTATION
1
3 2 6
5
4
HASHING
A function is a small task, that execute particular statement block. The function has two uses.
1. The result of the function is used as a kind of key in which the list is stored (i.e) the
function is used to determine where is the array to store the record.
2. Function is used as a method of ascending the record. This function is called HASH
function.
Hash Function = key mod 100
The remainder is used as an index in to array of employee records.
Example:
(00)
(01)
Key (02)
459250704 key mod 10024 (99)
COLLISIONS
The same address will occur that is called collisions.
Resolving collision techniques
1. Hash and search
2. Rehashing
3. Chaining
C
A
B D E
F
Hash function
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 67
1. HASH AND SEARCH
A Simple approach to resolving collision is to store the colliding element to next
available space.
Key 556677003 00
01
02
03
04
Try index 3
REHASHING
Another common technique for resolving collision is rehashing. If the first computation of
the hash function produce a collision, we can use hash address as the input to the rehash function
and computes new address.
Original hash function = key MOD 100
Rehash function = (key+1) MOD 100
Until find the empty address.
CHAINING OR BUCKET OR LIST METHOD
A third technique for handling collisions was the hash address not as the actual location of
the record, but as the index in to an array of pointers called buckets. Each bucket points to a
linked list or chain of records that share the same hash address.
00
01
02
09
H.P
Empty
02
12345003
04
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 68
HASHING RECHNIQUES
1. MID SQUARE METHOD
The key is multiplied by itself , and the central digits of the square are taken and
adjusted to fit the range of addresses.
Thus , if the record have 6-digits key and 1000 buckets are used , the key may be
squared to form a 12-digits field of which digits 5 to 8 are used. Thus if the key is
172148, the square is 02963493304. The central four digits are multiplied by 0.7 : 3493 *
0.7 = 2445. The 2445 is used as the bucket address.This is close to roulette-wheel
randomization and the result are usually found to the close to the theoretical result of
figure.
2 24
2 12 - 0
2 6 - 0
2 3 - 0
2 1 - 1
ADDRESS = 00011
2. DIVIDING
It is possible to find a method which gives better results than a random number
generator. A simple division method is such, the key is divided by a number
approximately equal to the number of available addresses, and the remainder is taken as
the relative bucket address, as in fig. A prime number or number with small factors is
used.
Thus if the key is 172148 again, and there are 7000 buckets, 172148 might be divided
by 6997. The remainder is 4220, and this is taken as the relative bucket address. One
reason division tends to give fewer overflows than a randomizing algorithm is that many
key set have tons of consecutive numbers, there by distributing.
3. SHIFTING
The outer digits of the key at both ends are record to overlap by an amount equal to
the address length, as shown in figure. The digits are then added, and the result is
adjusted to fit the range of bucket address.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 69
EXAMPLE
1 7 2 0
7 3 5 9
4. FOLDING
Digits in the key are folded inward like folding papers as shown in figure . The
digits are then added and adjusted as before. Folding tends to be more appropriate for
large keys.
EXAMPLE
1 7 2 0
7 3 5 9
5. DIGIT ANALYSIS
Some attempts at achieving an even spread of bucket addresses have analyzed the
distribution of values of each digit or character in the key. Those positions having the
most skewed distribution are deleted from the key in the hope that any transform applied
to the other digits will have a better chance of giving a uniform spread.
6. RADIX CONVERSION
The radix of a number may be converted for example to radix 11. The excess high
order digits may then be truncated. The key 172148 is converted to 1 *
115
+7*114
+2*113
+1*112
+4*111
+3*110
= 266373 and the digits 6763 are multiplied by
0.7 to give the relative bucket address 4461. Radix 11 conversion can be performed more
quickly in a computer y a series of shifts and additions.
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 70
7. LIN’S METHOD[Q]
In this method a key is expressed in radix p, and the result is taken modulo qm
,
where p and q are prime number (or numbers without small prime factors) and m is
positive integer.
The key 172148 would first be written as a binary string:0001 0111 0010 0001
0100 1000. Grouping the string in to group of three bits, we obtain 000 101 110 010 000
101 001 000 = 05610510. This is expressed as a decimal number and divided by a
constant qm
. The remainder is used to obtain the relative bucket address.
8. POLYNOMIAL DIVISION
Each digit of the key is regarded as a polynomial co-efficient, Thus the key
172148 is regarded as x5
+7x+4
+2x3
+x2
+4x1
+8x+0
. The polynomial so obtained is divided
by another unchanging polynomial. The co efficient in the remainder forms the basis of
the relative bucket address(x=2 or x=3).
SHORTEST PATH PROBLEM
DIJIKSTRA ALGORITHM
We have seen in the graph traversals that we can travel through edges of the graph. It is
very much likely in applications that these edges have some weights attached to it. They weight
may reflect distance time or some other quantity that corresponds to the cost we incur when we
travel through that edge. For example, in the graph in figure, we can go from Delhi to Andaman
Nicobar through Madras of a cost of 7 or through Calcutta at a cost of 5. In these and many other
applications we are often required to find a shortest path, i.e a path having the minimum weights
between of finding shortest path for directed graph in which every edge has a non negative
weight attached.
1
2
4
3
Let us at this stage recall how do we define a path . A path in a graph is sequences of
vertices such that there is an edge that we can follow between each consecutive pair of vertices
length of the path is the sum of weights of the edges of the path . The starting vertex of the path
DELHI
CALCUTTA
MADRAS
ANDAMAN
DATASTRUCTURE (CS &CA)
SIVASANKARI A Page 71
is called the source vertex and the last vertex of the path is called the destination vertex. Shortest
path from vertex V to vertex W is a path for which the sum of the weights of the arcs on edges
on the path is minimum. Here we must note that the path that may lock longer if we see the
number of edges and vertices visited, at times may be actually shorter cost wise. Also we have
two kinds of problem in finding shortest path. One could be that we have single source vertex
and we seek a shortest path from that source vertex V to every other vertex of the graph. It is
called single source shortest path problem.
Consider the weighted graph in figure with 8 nodes.
WEIGHTED GRAPH
2 1
2 2 4 3
4 6
1 3 3 7
5
There are many paths from A to H
Length of path AFDEH = 1+3+4+6= 14
Another path from A to H is ABCEH
It’s length is 2+2+3+6= 13
********************************ALL THE BEST*******************************
A
B
D
F
C
E
G
H
A
B
D
F
C
E
G
H

Weitere ähnliche Inhalte

Was ist angesagt?

Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021Sreedhar Chowdam
 
Data structures Basics
Data structures BasicsData structures Basics
Data structures BasicsDurgaDeviCbit
 
2 data structure in R
2 data structure in R2 data structure in R
2 data structure in Rnaroranisha
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structurekalyanineve
 
Day 1b R structures objects.pptx
Day 1b   R structures   objects.pptxDay 1b   R structures   objects.pptx
Day 1b R structures objects.pptxAdrien Melquiond
 
Data structure &amp; algorithms introduction
Data structure &amp; algorithms introductionData structure &amp; algorithms introduction
Data structure &amp; algorithms introductionSugandh Wafai
 
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMARIntroduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMARBHARATH KUMAR
 
Lecture 9 data structures and algorithms
Lecture 9 data structures and algorithmsLecture 9 data structures and algorithms
Lecture 9 data structures and algorithmsAakash deep Singhal
 
Day 1d R structures & objects: matrices and data frames.pptx
Day 1d   R structures & objects: matrices and data frames.pptxDay 1d   R structures & objects: matrices and data frames.pptx
Day 1d R structures & objects: matrices and data frames.pptxAdrien Melquiond
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil duttAnil Dutt
 
Day 5b statistical functions.pptx
Day 5b   statistical functions.pptxDay 5b   statistical functions.pptx
Day 5b statistical functions.pptxAdrien Melquiond
 
Data structure & its types
Data structure & its typesData structure & its types
Data structure & its typesRameesha Sadaqat
 

Was ist angesagt? (20)

Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021
 
Data structures Basics
Data structures BasicsData structures Basics
Data structures Basics
 
2 data structure in R
2 data structure in R2 data structure in R
2 data structure in R
 
Data structure using c++
Data structure using c++Data structure using c++
Data structure using c++
 
Data Structures
Data StructuresData Structures
Data Structures
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 
Day 1b R structures objects.pptx
Day 1b   R structures   objects.pptxDay 1b   R structures   objects.pptx
Day 1b R structures objects.pptx
 
Data structure &amp; algorithms introduction
Data structure &amp; algorithms introductionData structure &amp; algorithms introduction
Data structure &amp; algorithms introduction
 
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMARIntroduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
Introduction of Data Structures and Algorithms by GOWRU BHARATH KUMAR
 
Lecture 9 data structures and algorithms
Lecture 9 data structures and algorithmsLecture 9 data structures and algorithms
Lecture 9 data structures and algorithms
 
Day 1d R structures & objects: matrices and data frames.pptx
Day 1d   R structures & objects: matrices and data frames.pptxDay 1d   R structures & objects: matrices and data frames.pptx
Day 1d R structures & objects: matrices and data frames.pptx
 
Day 2b i/o.pptx
Day 2b   i/o.pptxDay 2b   i/o.pptx
Day 2b i/o.pptx
 
Day 2 repeats.pptx
Day 2 repeats.pptxDay 2 repeats.pptx
Day 2 repeats.pptx
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
Data structures using c
Data structures using cData structures using c
Data structures using c
 
Day 5b statistical functions.pptx
Day 5b   statistical functions.pptxDay 5b   statistical functions.pptx
Day 5b statistical functions.pptx
 
Data Structure Basics
Data Structure BasicsData Structure Basics
Data Structure Basics
 
Data structure & its types
Data structure & its typesData structure & its types
Data structure & its types
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 

Ähnlich wie DATA STRUCTURE BY SIVASANKARI

Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyMalikireddy Bramhananda Reddy
 
unit1Intro_final.pptx
unit1Intro_final.pptxunit1Intro_final.pptx
unit1Intro_final.pptxDEEPAK948083
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureRai University
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureRai University
 
data structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxdata structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxcoc7987515756
 
Introduction to Data Structure
Introduction to Data StructureIntroduction to Data Structure
Introduction to Data Structurechouguleamruta24
 
Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016) Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016) Ameer B. Alaasam
 
8074.pdf
8074.pdf8074.pdf
8074.pdfBAna36
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringRAJASEKHARV8
 
01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptx01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptxDwijBaxi
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxDEEPAK948083
 
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEVenugopalavarma Raja
 
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDev Chauhan
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1Kumar
 
Datastructures using c++
Datastructures using c++Datastructures using c++
Datastructures using c++Gopi Nath
 

Ähnlich wie DATA STRUCTURE BY SIVASANKARI (20)

Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada ReddyDatastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
 
unit1Intro_final.pptx
unit1Intro_final.pptxunit1Intro_final.pptx
unit1Intro_final.pptx
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
 
data structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxdata structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptx
 
DS_PPT.ppt
DS_PPT.pptDS_PPT.ppt
DS_PPT.ppt
 
Introduction to Data Structure
Introduction to Data StructureIntroduction to Data Structure
Introduction to Data Structure
 
Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016) Data structures "1" (Lectures 2015-2016)
Data structures "1" (Lectures 2015-2016)
 
DS_PPT.pptx
DS_PPT.pptxDS_PPT.pptx
DS_PPT.pptx
 
8074.pdf
8074.pdf8074.pdf
8074.pdf
 
M v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notesM v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notes
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
Dsa unit 1
Dsa unit 1Dsa unit 1
Dsa unit 1
 
01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptx01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptx
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptx
 
cluod.pdf
cluod.pdfcluod.pdf
cluod.pdf
 
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
 
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1
 
Datastructures using c++
Datastructures using c++Datastructures using c++
Datastructures using c++
 

Mehr von SivaSankari36

CLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARICLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARISivaSankari36
 
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARIMOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARISivaSankari36
 
JAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARIJAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARISivaSankari36
 
MOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARIMOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARISivaSankari36
 
PROGRAMMING IN JAVA- unit 5-part II
PROGRAMMING IN JAVA- unit 5-part IIPROGRAMMING IN JAVA- unit 5-part II
PROGRAMMING IN JAVA- unit 5-part IISivaSankari36
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part ISivaSankari36
 
PROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part IIPROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part IISivaSankari36
 
PROGRAMMING IN JAVA- unit 4-part I
PROGRAMMING IN JAVA- unit 4-part IPROGRAMMING IN JAVA- unit 4-part I
PROGRAMMING IN JAVA- unit 4-part ISivaSankari36
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IIPROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IISivaSankari36
 
Functional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data ApplicationFunctional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data ApplicationSivaSankari36
 
Java unit1 b- Java Operators to Methods
Java  unit1 b- Java Operators to MethodsJava  unit1 b- Java Operators to Methods
Java unit1 b- Java Operators to MethodsSivaSankari36
 
Java unit1 a- History of Java to string
Java unit1 a- History of Java to stringJava unit1 a- History of Java to string
Java unit1 a- History of Java to stringSivaSankari36
 

Mehr von SivaSankari36 (14)

CLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARICLOUD COMPUTING BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARI
 
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARIMOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
 
JAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARIJAVA BOOK BY SIVASANKARI
JAVA BOOK BY SIVASANKARI
 
MOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARIMOBILE COMPUTING BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARI
 
PROGRAMMING IN JAVA- unit 5-part II
PROGRAMMING IN JAVA- unit 5-part IIPROGRAMMING IN JAVA- unit 5-part II
PROGRAMMING IN JAVA- unit 5-part II
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part I
 
PROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part IIPROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part II
 
PROGRAMMING IN JAVA- unit 4-part I
PROGRAMMING IN JAVA- unit 4-part IPROGRAMMING IN JAVA- unit 4-part I
PROGRAMMING IN JAVA- unit 4-part I
 
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part IIPROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA-unit 3-part II
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
 
Functional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data ApplicationFunctional MRI using Apache Spark in Big Data Application
Functional MRI using Apache Spark in Big Data Application
 
Java unit1 b- Java Operators to Methods
Java  unit1 b- Java Operators to MethodsJava  unit1 b- Java Operators to Methods
Java unit1 b- Java Operators to Methods
 
Java unit1 a- History of Java to string
Java unit1 a- History of Java to stringJava unit1 a- History of Java to string
Java unit1 a- History of Java to string
 

Kürzlich hochgeladen

URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 

Kürzlich hochgeladen (20)

URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 

DATA STRUCTURE BY SIVASANKARI

  • 1. DATA STRUCTURE A. SIVASANKARI MSc., M.Phil., DCP., HEAD OF THE DEPARTMENT, DEPT OF COMPUTER SCIENCE, D.K.M. COLLEGE FOR WOMEN (AUTONOMOUS) SAINATHAPURAM, VELLORE-1.
  • 2. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 2 ACKNOWLEDGEMENTS It is my immense pleasure to offer my first and foremost gratitude to the Almighty God for giving me the power to believe in myself and pursue my dreams. I would like to express my gratitude to my Father B.M.Arunachalam, Mother A.Kalaiarasi and Brother Dr. A. Dineshkarthik for their love, encouragement and support. I offer my humble gratitude to our honourable Secretary Mr.D.Maninathan, BE., for permitting me to bring out this book and for their valuable advice. I would like to extend my heartfelt gratitude to our beloved Principal Dr.P.N.Sudha Ph.D., for permitting me to bring out this book and for their valuable appreciation advice and blessings. I wish to express my profound thanks to my Colleagues and my well- wishers Dr.M.Sobia and R.Rajeshbabu for their moral support and encouragement in making this book a reality. I also thank all my Friends and Students who supported directly or indirectly to bring out this book in good direction. I am happy to express my thanks to the publisher and the entire team of Publications, who have taken immense pain to get this book. I wish our readers all the very best in their all endeavours. SIVASANKARI
  • 3. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 3 UNIT-I DATA STRUCTURE Data are represented by data values held temporarily within programs data area or recorded permanently on a file often the different data values are related to each other. To enable programs to make use of these relationship. These data values must be in an organized form. The organized collection of data is called a data structure. The program have to follow certain values to access and process. An Organized collection of data is called data structure. Data may be organized in many different ways, the logical or mathematical model of a particular organization of the data is called structure. Data Structure : Organized data allowed operator alternative definition is d=[DFA]->D means –Set of Domains F Means-Set of Functions A Means –Set of Axioms A Triple set of DFA is called data structure which is denoted by Symbol d. DIFFERENT TYPES OF DATA STRUCTURE (OR) CLASSIFICATION OF DATA STRUCTURE 1.We may classify the data structures as Linear and Non Linear Data Structure. In Linear data structure the data item are arranged in a linear sequence line an array. In a Non-Linear the data item are not in a sequence an example of a Non-Linear data structure is TREE. 2.Data structure may also classified as Homogeneous(Ex: Array) and Non-Homogeneous(Ex: Record) Data Structure).An Array is a Homogeneous Structure in which all elements are of same type records are a common example of Non-Homogeneous data Structure. 3.Another way of Classifying data structure is a static or dynamic data structure .A Static structure are one whose sizes and structures are associated memory locations are fixed at compile time. Dynamic structure are one which expand or shrink required during the program execution and their associated memory location change. Records are a common example of non- Homogeneous data structure. 4. Another way of classifying data structure is primitive and non-Primitive. Another name of Primitive data structure is standard data structure. Non-Primitive data structure is called as composite.
  • 4. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 4 DATA STRUCTURE PRIMITIVE[STANDARDDATA TYPE] NON-PRIMITIVE[COMPOSITE DATA TYPE] EXAMPLE EXAMPLE 1. INT 1. FILE 2. REAL 2. LIST[LINEAR,NON-LINEAR] 3. LONG INT 3. STACK 4. STRING 4. ARRAY 5.QUEUE PRIMITIVE DATA STRUCTURE NUMBER SYSTEM [BINARY,OCTAL,DECIMAL,HEXA-DECIMAL] Numbers are used symbolically to represent quantities of objects. Number system such as Roman Number system, Positional Number System. ROMAN NUMBER SYSTEM ------ I,II,III,IV POSITIONAL NUMBER SYSTEM ------- Decimal, Binary number system Example: 329-Decimal ------300+20+9 3*102 +2*101 +9*100 0,1,2 are Positional weights. Example: 10110 1*24 +0*23 +1*22 +1*21 +0*20 COMPLIMENTS  1’s ,2’s,9’s,10’s with examples. INT  Long int  Short Int  Signed  UnSigned FLOATING POINT  Real Number
  • 5. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 5 CHARCTER INFORMATION  BCDIC and ASCII LOGICAL IMMPLEMENTATION INFORMATION  And  OR  Not NON-PRIMITIVE DATA STRUCTURE Non-Primitive Data structure can be classified as Arrays, List and Files. ARRAY 1. An Array is an ordered set which consist of a fixed number or objects. 2. No deletion or insertion operations are performed on arrays. At best elements can be changed to a value which represents an element to be ignored. List 1. A List is an ordered set consisting of a variable number of elements to which insertion and deletion can be made. 2. A List which displays the relationship of adjacency between elements is said to be linear. And other List is said to Non-Linear. Data Data is a element such as number,character etc… [information raw data fact] Field A collection of data is called as Field [name, sex..] Record A Collection of field is called Record File A Collection of record is called as file Stack Last in First out Queue First in first out
  • 6. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 6 OPERATION ON DATA STRUCTURE 1. CREATION An operation frequently used in conjunction with data structure is one which create a data structure. This operation will be called CREATION Operation. 2. DESTROY One which destroys the operation, the operation is called DESTROY Operation. 3. SELECTION [access] The most frequently used operation associated with data structure is one that the programmer uses to access data within a data structure. This type of operation is known as SELECTION Operation. 4. UPDATE [Changing the Data] Another operation used in Conjunction with data structure is one which changes data structure. This operation will be called an UPDATE. ASYMTOTIC NOTATION [0,Ω,Θ] 1. [Big ‘oh’] The function f(n)=o(g(n)) (Read as f of n is big oh of g of n) if(if and only if)their exist positive constants c and n0 .Such that f(n)<=c*g(n)) for all n, n>=n0. 2. [Omega] The function f(n)= Ω(g(n)) (Read as f of n is omega of g of n)if their exist positive constant c and n0.such that f(n)>=c*g(n) for all n, n>=n0. 3. [Theta] The function f(n)= Θ(g(n)) (Read as f of n is Theta of g of n)if there exist +ve constant c1,c2 and n0 .such that c1,g(n)<=f(n)<=c2g(n) forn,n>=n0. 4. [Little ‘oh’]The function f(n)=o(g(n)) (Read as of n is Little oh of g of n)if , 𝑛 → ∞ 𝑓(𝑛)/g(n)=n->∞ 𝑓(𝑛) 𝑔(𝑛) = 0 5. [Little Omega]The function f(n)=w(g(n)) (Read as ‘F of n is little omega of g of n’)if, lim n → ∞ g(n) f(n) = 0 ARRAY 1. Array is an ordered set which consists of a fixed number of objects. 2. No deletion or insertion operations are performed on array. At best elements can be changed to a value which represent an element to be ignored. 3. Array can be classified as one dimensional, two dimensional and Multi-dimensional.
  • 7. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 7 ONE –DIMENSIONAL ARRAY The simplest form of an array is a one dimensional array or vector the various element of an array are distinguished by giving each piece of data separate index or subscript. The subscript of an element designate its position in arrays ordering. An array named which consists on N elements can be depicted as shown in figure. Representation of a Vector LO-1 1 Where Lo=> is starting Position C=> Mention the type of array .. i=> Finding Position Member Lo+c(i-1)-->A[i]---- A[i] Another Representation A(1) A(2)…………………………………………………………………….A(n) If we want to find A[10] Loc a[5] = L0 + c * (I-1) = 1 + 1* (5-1) 5 = 1 + 4 5 = 5 TWO DIMENSIONAL ARRAY Any Array Defined To Have More Than One Dimension Is Considered To Be Multi Dimensional Array. An array can be 2,3,4 or N dimensional array. Two dimensional arrays, sometimes called matrices. This array is to visualize a table column and rows. The first dimension in the array refer to the row, and the second dimension refers to the columns.
  • 8. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 8 Example: A Collection of data about the grades of students in a class in the four different exams can be represented using a two dimensional array. If we have 10 students and each given grades in 4 exams, we can depict it as in the table(fig 2) Grade Student Number Each cell in this table contains a grade value for the student number (given by the corresponding row number) and exam number)(g and exam number)(given by the corresponding column number). An array A of order [0*4.A[I,j] represent an element of A. Where I runs from to 10 and J runs from 1 to 4 A[3,4]]will have the grade value of 8th Student in first exam and so on. [Loc A[I,j]=L0 + (i-1) *(j-1) ] In General an array of the order M*N consist of M rows, N Columns and MN elements. It may be depicted as 1 , 2 , ……………………………………………….N 1 2 . . M OPERATIONS AN ARRAY The array is homogeneous structure (I,e) the element of an array are the same type . Following set of operations are defined for this structure. 1. Creating an array 2. Initializing an array 3. Storing an element 4. Ret riving an element 5. Inserting an element 1 2 3 4 1 2 3 4 5 6 7 8 9 10
  • 9. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 9 6. Deleting an element 7. Searching for an element 8. Sorting element 9. Printing an array STORAGE OF ARRAYS IN MAIN MEMORY The data represented in an array is an array is actually stored in the Memory cells of the machine Because computer’s memory is linear, a one dimension array can be mapped. Onto the memory cells in a rather straight forward manner. Storage for element A[I+1] will be adjacent to storage for elements BCD for I=1 to n to find the actual address of an elements . One Merely needs to subtract one from the position of the desired entry. And then add the result to the address of the first cell in the sequence. Two dimensional array, we think of data being arranged in rows and columns. However machine’s memory is arranged as a row of memory cells. Then the rectangular structure of a two dimensional array must be stimulated. We first calculate the amount of storage area needed and allocate a block of contiguous memory cells of that size on way to score the data in the cells is row by row. That is we store first, the first row of that array and the second row of the array and then the next and soon. For Example :- The array defined by a which logically appears as given in figure. Int [3][4] A[0][0] A[0][1] A[0][2] A[0][3] A[1][0] A[1][1] A[1][2] A[1][3] A[2][0] A[2][1] A[2][2] A[2][3] A[0][0] A[0][1] A[0][2] A[0][3] A[1][0]  A[1][1] A[1][2] A[1][3] A[2][0] A[2][1] A[2][2] A[2][3] Appears physically as given in row major representation. Such a storage scheme is called row major order. The other alternative is to store the array column by column, it is called column, it is called column major order. A[0][0] A[0][1] A[0][2] A[0][3] A[1][0] A[1][1] A[1][2] A[1][3] A[2][0] A[2][1] A[2][2] A[2][3]
  • 10. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 10 OPERATION ON ARRAY 1. To find the location  Single Dimensional  Two Dimensional SINGLE DIMENSIONAL EXAMPLE: FORMULA: Loc A[i]= L0 + c *I – 1 A[10]=A[0],A[1],----------------------a[9] To Find the Location of a[5] Loc A[i] = L0 + C * I – 1 Where I = Position of the Location L0 = First Position of Array C = Mention the dimensional type Loc A[5]= L0 + c * (i-1) A[5]= 1 +1 * [5-1] A[5] = 1 + 1 * 4 A[5] = 1 + 4 A[5] = 5 TWO DIMENSIONAL ARRAY Row Major Order : Loc A[I,j]=L0 + [i-1] *n + (j-1) Column Major Order : Loc A[I,j]=L0 + [j-1] *m+(i-1) Where i = Row Position J= Column Position m=row of the given matrix n=Column of the given matrix Lo= 1 st Position of the given matrix
  • 11. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 11 The given matrix is [6,4] Representation of given matrix = A[1][1]A[1][2]A[1][3]A[1][4] A[2][1]A[2][2]A[2][3]A[2][4] A[3][1]A[3][2]A[3][3]A[3][4] A[4][1]A[4][2]A[4][3]A[4][4] A[5][1]A[5][2]A[5][3]A[5][4] A[6][1]A[6][2]A[6][3]A[6][4] ROW MAJOR ORDER Loc A[I,j]=L0 + [i-1] *n + [j-1] Loc A[3,2] = 1 + [3-1] * 4 +[2-1] = 1+ 2 * 4 + 1 = 1 + 8 + 1 Loc A[3,2] = 10 COLUMN MAJOR ORDER The Given matrix is [6,4] Representation of Given matrix = A[1][1] A[1][2]A[1][3]A[1][4] = A[2][1]A[2][2]A[2][3]A[2][4] = A[3][1]A[3][2]A[3][3]A[3][4] = A[4][1]A[4][2]A[4][3]A[4][4] = A[5][1]A[5][2]A[5][3]A[5][4] = A[6][1]A[6][2]A[6][3]A[6][4] Loc A[I,j] = Lo + [j-1]m + [i-1] Loc A[3,2]= 1 + (2-1) 6 + (3-1) Loc A[3,2]= 1 + 6 + 2 Loc A[3,2] = 9
  • 12. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 12 UNIT – II STACK AND QUEUE NON-PRIMITIVE DATA TYPE STACK One of the most important linear data structure of variable size is the stack. Example : Pile of Tray (pile-stack) DEFINITION In the most general form of a linear list we are allowed to delete an element from and insert on to any portion in the list. An important subclass of lists permits the insertion on deletion of an element to occur only at any end. A Linear list belonging to the subclass is called a stack. This insertion operation is referred to as PUSH and the deletion Operation as POP. The most and the least accessible elements in a stack are known as top and bottom of the stack respectively. Since insertion and deletion operations are performed at one end of the stack, the elements can only be removed in the opposite order from that in they were added to the stack. A Linear list is frequently referred to as a LIFO List, Which means “LAST IN FIRST OUT”. Example: A common example of a stack phenomenon which permits the selection of only its end element is a pile of trays in Cafeteria. DIAGRAM REPRESENTATION TOP TRAY OF FILE Stacked Trays Spring
  • 13. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 13 Another example of a stack is a railway system for shunting cars as shown in the diagram. In this system the last railway can to be placed on the stack is the first to leave. Using repeatedly the insertion and deletion operation permits that cars, to be arranged on the output railway line in various orders. OUTPUT DELETION STACK The operation on a stack are stimulated by a vector consisting of some large number of elements which should be sufficient in number to handle all possible insertions likely to be made to stack. A Pointer top keeps track of the top elements in the stack. Initially when the stack is empty top has a value ‘0’ and when the stack contains a single element top has the value ‘1’ and soon. Each time a new elements is inserted in the stack, the pointer is incremented by 1, before the element is placed on the stack. The pointer is decremented by 1,each time the deletion is made from the stack. Bottom of stack Vector of elements representing a stack Top of Stack Unused Stack A more suitable representation of a stack is given in the stack represent the top element. The left most occupied element of the stack represent its bottom element.
  • 14. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 14 ALTERNATIVE REPRESENTATION OF STACK DELETION INSERTION BOTTOM TOP UNUSED STACK OPERATIONS ON A STACK The algorithm for insertion and deleting an element from a stack are given below 1. PROCEDURE PUSH(S,TOP,X) This procedure inserts an element a to the top of a stack which is represented by a vector s containing N elements with a pointer top denoting the top elements in the stack. 1. [Check for stack overflow] If top>=N Then write (Stack Overflow) Return 2. [Increment Top] TopTop +1 3. [Insert element] S[Top] x 4. [Finished] Return 2. FUNCTION POP(S,TOP) This function removes the top element from a stack which is represented b a vector a and returns this element. Top is a pointer to the top element of the sack. 1. [Check for underflow on stack] If Top=0 Then write(STACK UNDERFLOW ON POP) Take action in response to underflow Exit
  • 15. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 15 2. [Decrement pointer] Top  Top-1 3. [Return for met top element of stack] Return (S[top+1]) 4. [Finished] 3. FUNCTION PEEP(S,TOP,I) Given a vector S (Consisting of N elements S) represent a sequentially allocated stack and a pointer top denoting the top elements of the stak. This function return the value of the I th element from the top of the stack. The element is not deleted by this function 1. [Check for stack underflow] If Top- I + 1 <=0 Then write (STACK UNDERFLOW ON PEEP) Take action in response to underflow Exit 2. [Return I th element from top of stack] Return (S[Top – I + 1]) 4. PROCEDURE CHANGE (S,TOP,X,I) As before a vector S(containing of N elements)represent a sequentially allocated stack and a pointer top denotes the Top element of the stack. This procedure changes the value of the Ith element from the top of the stack to the value contained in X. 1. [Check for stack underflow] If Top – I + 1 <=0 Then write (STACK UNDERFLOW ON CHANGE) Return 2. [Change I th element from Top to Stack] S[TOP – I + 1] X 3. [Finished] Return. APPLICATION OF STACK The first application deals with recursion. The second application of a stack is classical, it deals with the compilation of infix expressions in to object code 1. RECURSION A property or a set P can be specified by an inductive definition. An inductive definition of a set can be realized by using a given finite set of elements. A and the following three classes :Basis, inductive and external class.
  • 16. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 16 A Vector Representation Of n Stack S[1]---------------------------------------------------------------------------------------------S[M] B[1]+[1] B[2]+[2] B[N]+B[N] B[N+1] The factorial function, whose domain is natural number, can be recursively defined as, 1 IF N = 0 FACTORIAL = N * FACTORIAL(N-1) OTHERWISE Here FACTORIAL(N) is defined in terms of FACTORIAL(N-1) which in turn is defined in terms of FACTORIAL(N-2) etc. Until finally FACTORIAL(0) is reached, whose value is given as “ONE”. A recursive definition of a set or process must contain an explicit definition for particular vales(s) of the argument(s).Otherwise the definition could never change. An important facility available to the program is the procedure (function or subroutine).A procedure that contains a procedure call to itself, or a procedure call to a second procedure which eventually causes the first procedure to be called is known as “Recursive’ procedure. There are two conditions that must be satisfied by and recursive procedure. 1. Each time a procedure calls itself (either directly or indirectly) it must be nearer in some sense to a solution. In the case of the factorial function, each time that the function calls itself its argument is decremented by ‘ONE’. So the argument of the function is getting smaller. 2. Second , there must be a decision criterion for stopping, the process or computation. In the factorial function the value of n must be zero. There re essentially two types of recursion. The first type concerns recursively defined function.(or primitive recursive function)an example of this kind is the factorial function. The second type is recursion). A typical example of this kind is Ackerman’s function which is defined as,
  • 17. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 17 N+1, if m=0 A(M,N) = A(M-1 , 1 ) , if n= 0 A (M -1), A(M, N-1), OTHERWISE Primitive recursive function can be solved iteratively. A Iterative process can be illustrated with the aid of the flow chart given below: There are four parts in this process, 1. Initialization 2. Decision 3. Computation (Calculation) 4. Updation (Change) Initialization The parameters of the function and a decision parameter in this part are set to there initial values. The decision parameter is used to determine when to exit from loop. Decision The Decision parameter decides whether to remain in the loop. Computation The Required computation is performed in this part. Updation The decision parameter is updated and a transfer to the next iteration results. Recursion is becoming increasingly important in symbol manipulation and non-numeric applications. Done Not Not Done ENTRY INITIALIZATION DECISION COMPUTATION RETURN UPDATE
  • 18. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 18 The general algorithm model for any recursive procedures contain the following steps: 1. [PROLOGUE] Save the parameters, local variables and return address. 2. [BODY]I f the base criterion has been reached then perform the final computation and goto step3,Otherwise perform the partial computation and goto Step1. 3. [EPILOGUE]Restore the most recently saved parameters local variable and return address, go to this return address. A Flow chart model for this algorithm is given the model consists of a prologue, a body and an epilogue. The purpose of the prologue is to save the formal parameters, local variable and return address and that of epilogue is to restore them. Note that the parameters, local variables and return address that are restored are those which were most recently(i.e) the last saved are the first to be restored (LIFO). The body of the procedure contains a procedure call to itself. In fact, They may be more than one call to itself in certain procedures. The keybox contained in the body of the procedure is the one which invokes a call to itself. The dotted-line exit from this box indicated that a call to itself is being initiated within the same procedure. Each time a procedure saves all necessary information required for its proper functioning. 4. The procedure body contains two computation boxes namely, the partial and final computation boxes frequently the partial computation box is combined with the Values of the arguments. The procedure call box(Updation box). (This is case for computation of the factorial function). The final computation box gives the explicit definition of the process for same values or values of the arguments. The test box determines whether the arguments values(s) in that for which explicit definition of the procedure is given,[Characteristic associated with each call to(entry into a recursive procedure is a level number. The entry in to the procedure due to the initial call from the main program is given the level number ‘one’ as the main program is assumed to have level number ‘Zero’. Each subsequent entry in to the procedure has an associated level number ‘one’, higher than the level number of the procedure from which the call was made. Another characteristic of the recursive procedure, in the depth of recursion, which is the number of times the procedure is called recursively in the process of evaluating a given argument or arguments, usually the quantity is not obvious, except in the case of extremely simple recursive functions. Such as factorial(N) for which the depth is N. 5. The last -in and first-out characteristic of a recursive procedure suggest that a stack is the most obvious data structure to use to implement step1 and three of this procedure. At each time procedure call (or level of recursion) the stack is pushed to save the necessary values, upon exit from that level, the stack is pushed to save the ‘popped’ to restore the saves values of the proceeding (or calling level).
  • 19. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 19 The recursive mechanism is best described by an example. Consider as algorithm to calculate factorial(N)recursively which explicitly shows the recursive frame work. FACTORIAL Given an integer N, this algorithm computers N. The stack A is used to store an activation record associated with each recursive call. Each activation records contains the current value of N & the current return address (RET-ADDRESS). TEMP-REC is also a record which contains two variables (PARM and ADDRESS). This temporary recorders required to simulate the proper transfer of control from one activation record of algorithm FACTORIAL to another. Whenever a temp-rec is placed on the stack A, copies of PARM and ADDRESS are pushed on to A and assigned to N and RET-ADDRESS respectively. Top points to the top element of stack A and its value is initially 0. Initially ,the return address is set to the main calling address.(i.e. ADDRESSMain address) PARM 2 is set to the initial values of N2. 1. [save N and return address] Call PUSH[A,TOP,TEMP-REC] 2. [Is base criterion found] If N=0 then Go to step 4 Else PARM N-1 ADDRESS step 3 Go to step 1 3. [Calculate N] FACTORIAL N * FACTORIAL 4. [Restore previous N and return address] TEMP-RECPOP(A,TOP) (i.e., PARM N) ADDRESS RET-ADDR Go to ADDRESS
  • 20. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 20 EXAMPLE LEVEL NO DESCRIPTION STACK A CONTAINS 1 1.PUSH[A,0 (2,MAIN ADDRESS)] 2.If n≠0 PARMN-12-1==>1 ADDRESS STEP 3 TOP VALUE 2 1.PUSH [A,1(1,STEP 3)] IF N≠ 0 PARMN-11-1==> 0 2. ADDRESS STEP 3 TOP VALUE Top 3 1. PUSH[A,2(0,STEP 3)] 2.N=O FACTORIAL1 TOP Top RETURN 4. TEMP.RECPOP(A,STEP 3) ENTER LEVEL 2 3.FACTORIAL1 *1 4.TEMPPOP(A,STEP 3) GO TO STEP 3 Top RETURN ENTER LEVEL 1 5.FACT2*1==>2 TEMP REC-POP(A,MAINADD) GO TO MAIN ADDRESS Top 2 1 Main Add Step 3 2 1 0 Main Add Step 3 Step 3 2 1 Main Add Step 3 2 Main Add 2 MAIN ADDRESS
  • 21. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 21 PROGRAM FOR FACTORIAL # INCLUDE <IOSTREAM.H> VOID MAIN() INT FACT=1,N,I; CIN>>N; FOR(I=1,I<=N;I++) FACT=FACT*I; } COUT<<FACT; } 2. TOWER OF HANOI Another complex recursive problem is that of the tower of Hanoi has a historical basis in the virtual of the ancient tower of Brahma. The Problem is as follows Given N discs of decreasing size stack on one needle and two empty needles, it is required to stack all the discs onto a second needle in decreasing order of size. The third needle may be used as Temporary Storage. The movements of disc is restricted by the following rules, i) Only one drive may be moved at a time. ii) A Disc may be moved from any needle to any other iii) At no time may a larger discs rest upon a smaller disc. PICTURE OF HANOI (A) (B) (C)
  • 22. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 22 STEPS ARE 1. A TO C 2. A TO B 3. C TO B 4. A TO C 5. B TO A 6. B TO C 7. A TO C The solution on this problem is most clearly seen with the aid of induction. To move one disc, merely move it from needle A to needle C. To move two disc, move the first disc to needle B, move the second from needle A to needle C, then move the disc from needle B to C. In general , the solution of the problem of moving discs from needle A to needle C has three types, 1. Move N-1 disc from A to B 2. Move discs from A to C 3. Move N-1 discs from B to C. A close examination of the first and third steps will reveal that they are recursive in nature, A General algorithm for solving the tower of Hanoi problem is now given, i) Push parameters and return address on Stack. ii) If the stopping value has been reached then pop the stack to return to previous level else move all expect the final disc from starting to intermediate needle. iii) Move final disc from start to destination needle . iv) Move remaining discs from intermediately to destination needle. v) Return to previous level by popping stack. ALGORITHM 1. [SAVE PARAMETER AND RETURN ADDRESS] CALL PUSH (ST,TOP,TEMP-REC) THE EFFECT OF THE PUSH OPERATION IS AS FOLLOWS TOPTOP+1,N[TOP]N-VALUE,SN[TOP]SN-VALUE,IN[TOP]IN- VALUE,DN[TOP]DN-VALUE,RETADDR[TOP]ADDRESS) 2. [TEST FOR STOPPING VALUE OF N, IF NOT REACHED MOVE N-1 DISCS FROM START NEEDLE TO INTERMEDIATE NEEDLE] IF N[TOP]=0 THEN GO TO RET-ADDR[TOP] ELSE
  • 23. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 23 N-VALUE N[TOP]-1 SN-VALUESN[TOP] IN-VALUEDN[TOP] DN-VALUEIN[TOP] ADDRESSSTEP 3 GO TO STEP 1 3. [MOVE N TH DISC FROM START TO DESTINATION NEEDLE MOVE N-1 DISCS FROM INTERMEDIATE TO DESTINATION NEEDLE] TEMP-RECPOP(ST,TOP) WRITE (‘DISC’,N,’FROM NEEDLE’,SN,’TO NEEDLE,DN) N-VALUEN[TOP] SN-VALUEIN[TOP] IN-VALUESN[TOP] DIAGRAM REPRESENTATION LEVEL NO DESCRIPTION STACK CONTAINS 1. STEP1:PUSH[ST,0(2,A,B,C,MAINADDS) STEP2: IF N≠0 N-VALUEN[TOP]-1 SN-VALUESN[TOP] A IN-VALUEDN[TOP] C DN-VALUEIN[TOP] B RET-ADDRESS STEP 3 GO TO STEP 1 TOP AC 2. STEP 1:PUSH[ST,1(1,A,C,B,STEP 3)] STEP 2:IF N≠0 N-VALUEN[TOP]-1 SN-VALUESN[TOP] A IN-VALUEDN[TOP] B DN-VALUEIN[TOP] C RET-ADDRESS STEP 3 GO TO STEP 1 TOP AB N 2 SN A IN B DN C RE Main address 2 1 A A B C C B Main address STEP 3
  • 24. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 24 3. STEP 1:PUSH[ST,2(0,A,B,C,STEP3)] STEP 2: IF N=0 POP(ST,TOP) N-VALUEN[TOP]-1 SN-VALUEIN[TOP] B IN-VALUESN[TOP] A DN-VALUEDN[TOP] C RET-ADDRESS[TOP] TOP AC 4. POP(ST,TOP) WRITE(DISC 1 A TO B) N-VALUEN[TOP]-1=0 SN-VALUEIN[TOP] C IN-VALUESN[TOP] A DN-VALUEDN[TOP] B RET-ADDRESSSTEP 4 TOP CB STEP 4: POP(ST,TOP)3 2(ST,TOP) GO TO RET-ADDR WRITE (DISC 2 FROM A TO C) N-VALUE2-1 SN-VALUEB IN-VALUEA DN-VALUEC ADDRESSSTEP 4 GO TO STEP 1 TOP AC &BC 5. STEP 1:PUSH[ST,1(1,B,A,C,STEP 4)] STEP 2:IF N≠0 N-VALUE1-1 SN-VALUEB IN-VALUEC DN-VALUEA ADDRESSST3P 3 GO TO STEP 1 STEP 3: DN-VALUEDN[TOP] TOP BA ADDRESSSTEP 4 GO TO STEP 4 2 1 0 A A A B C B C B C Main address Step 3 Step3 2 1 0 A A C B B A C C B Main address Step 3 Step4 N 2 1 SN A B IN B A DN C C RE Main address Step 4 2 1 0 A B B B A C C C A Main address STEP 3 STEP 3
  • 25. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 25 STEP 4: [RETURN TO PREVIOUS LEVEL] TEMP-RECPOP(ST,TOP) GO TO REC-ADDR 3.INFIX, POSTFIX AND PREFIX NOTATIONS Every expression can be denoted in 3 types and they are i) Infix Notation ii) Postfix or polish or reverse polish notation iii) Prefix notation INFIX The expressions which are in normal format is known as infix notation. In this type the operation lies between the two variables. Ex: A+B PREFIX In prefix notation the operator comes first followed by two operands. Ex:+AB POSTFIX In Postfix notation the operands comes first followed by the operator Ex: AB+ ALGORITHM : REVERSE POLISH REV-POL Given an input string infix containing an infix expression which has been P added on the right with ‘(‘ and whose symbols have precedence values given by tables, a vector ‘S’ used as a stack and function ‘NEXTCHAR’ which when invoked returns the next character of its arguments, this algorithm converts INFIX TO REVERSE POLISH and places the results in string polish. The integer variable Top denotes the top of the stack algorithm. PUSH & POP are used for stack manipulation. The integer variables rank accumulates the rank of the expression. Finally, the string variable TEMP is used for temporary storage purpose.
  • 26. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 26 1. [Initialize stack] Top 1 S[TOP]’(‘ 2. [INITIALIZE OUTPUT STRING AND RANK COUNT] POLISH”0” OR ” “ RANK0 3. [GET 1ST INPUT SYMBOL] NEXTNEXT CHAR (INFIX) 4. [TRANSLATE THE INFIX EXPRESSION] REPEAT THROUGH STEP-7 WHILE NEXT ≠” “ 5. [REMOVE SYMBOLS WITH GREATE PRECEDENCE FROM STACK] IF TOP< 1 THEN WRITE (‘INVALID’) EXIT REPEAT WHILE F(NEXT)<G(S[TOP]) TEMPPOP(S,TOP) POLISHPOLISH ‘0’ TEMP RANK<-RANK + R[TEMP] IF RANK< 1 THEN WRITE (‘INVALID’) EXIT 6. [ARE THERE MATCHING PARANTHESIS] IF F(NEXT) ≠G (S[TOP]) THEN CALL PUSH (S,TOP,NEXT) ELSE POP (S,TOP) 7. [GET NEXT INPUT SYMBOL] NEXTNEXT CHAR(INFIX) IF TOP≠0 OR RANK≠1 THEN WRITE (‘INVALID’) ELSE WRITE(‘VALID’) EXIT A trace of the stack contents and the polish string ‘POLISH’ for the infix expression. Q=A+(B*C-(D/E^/F)*G)*H P=ABC*DEF^/G*-H*+
  • 27. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 27 PRECEDENCE TABLE SYMBOL INPUT PRECEDENCE FUNCTION OF F STACK PRECEDENCE FUNCTIONING G RANK FUNCTION R +,- 1 2 -1 *,/ 3 4 -1 6 5 -1 Variable 7 8 1 ( 9 0 - ) 0 - - SYMBOL SCANNED STACK EXPRESSION P ( A ( A + (+ A ( (+( A B (+(* AB * (+(* AB C (+( ABC - (+(- ABC* ( (+(-( ABC* D (+(-( ABC*D / (+(-(/ ABC*D E (+(-(/ ABC*DE ^ (+(-(/^ ABC*DE F (+(-(/^ ABC*DEF ) (+(- ABC*DEF^/ * (+(-* ABC*DEF^/ G (+(-* ABC*DEF^/G ) (+ ABC*DEF^/G*- * (+* ABC*DEF^/G*- H (+* ABC*DEF^/G*-H ) ABC*DEF^/G*-H*+ QUEUES Another important subclass of lists permits deletion to be performed at one end of a list and insertion at the other. The information in such as list is processed in the same order as it was received that is on a FIRST IN FIRST OUT (FIFO)Or a FIRST COME FIRST SERVED(FCFS) basis. This type of list is frequently referred to as a queue.
  • 28. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 28 Following figure is a representation of a queue illustrating how an insertion is made to the right of the most element in the queue and how a deletion consists of deleting the left most element in the queue. REPRESENTATION OF QUEUE FRONT REAR INSERTION DELETION The familiar and traditional chain of a queue in a check outline at a super mark cash register. The first person in line is usually the first to be checked out. A final example of a queue is the line of cars waiting to proceed in some fixed direction at an insertion of streets. The deletion of a car corresponds to the first car in the line passing through the intersection, while an insertion to the queue consists waiting the end of the line of existing cars waiting to proceed through the intersection. PROCEDURE QUEUE INSERT(Q,F,R,N,Y) Given F and R pointers to the front and rear elements of a queue ,a queue consisting of N elements and y elements, this procedure inserts Y at the rear of a Queue. Prior to the first invocation of the procedure F and R have been set to Zero. 1. [OVERFLOW] IF R>=N THEN WRITE (‘OVER FLOW’) RETURN 2. [INCREMENT REAR POINTER] RR+1 3. [INSERT ELEMENT] Q [R]Y 4. [IS FRONT POINTER PROPERLY SET?] IF F=0 THEN F1 RETURN The following algorithm deletes an elements from a queue. FUNCTION Q DELETE(Q,F,R)
  • 29. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 29 Given F and R the pointers to the front and rear elements of a queue respectively and the queue Q to which they correspond this function deletes and returns the last elements of the queue y is a temporary variable. 1.[UNDERFLOW] IF F=O THEN WRITE (‘UNDERFLOW’) RETURN(O) 0DENOTES AN EMPTY QUEUE 2. [DELETE ELEMENTS] YQ[F] (Y IS ITEM) 3. [QUEUE EMPTY] IF F=R THEN FR0 ELSE FF+1 (INCREMENT FRONT POINTER) 4. [RETURN ELEMENT] RETURN [Y] CIRCULAR QUEUE Circular queue are the ones implemented in circular from rather than a straight line. Circular queues overcome the problem of unutilized space in the linear queues. The circular queue considers at opposite end, that is why, if the space is there in the beginning , the rear shifts back to beginning after reaching the max, possible storage. REAR FRONT PROCEDURE FOR INSERTION 1. [RESET REAR POINTER] IF R=N THEN R1 ELSE RR+1 2. [OVERFLOW] IF F=R THEN WRITE[‘OVERFLOW’]
  • 30. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 30 RETURN 3. [INSERT ELEMENT] Q[R]Y 4. [IF FRONT POINTER PROPERLY SET] IF F=0 THEN F1 RETURN PROCEDURE FOR DELETION 1. [UNDERFLOW] IF F=0 THEN WRITE (‘UNDERFLOW’) RETURN (0) 2. [DELETE ELEMENT] YQ[F] 3. [QUEUE EMPTY] IF F=R THEN FR0 RETURN [Y] DEQUEUE DEQUEUE (DOUBLE ENDED QUEUE) is a linear list in which insertion and deletion are made to or from either end of the structure. Such a structure can be represented by the following diagram. DELETION INSERTION DELETION REAR
  • 31. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 31 INSERTION FRONT It is clear that a dequeue is more general than a stack or a queue. There are two variation of a dequeue namely 1. The input restricted dequeue 2. The output restricted dequeue. The input restricted dequeue allows insertion at only one end, while an output restricted dequeue permits deletions from only one end. PRIORITY : Q Adding and Deleting is according to the priority.
  • 32. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 32 UNIT III LINKED LISTS DEFINITION A list has been defined to consists of an ordered set of elements which may vary in number. A simple way to represent a linear list in to expand each mode to contain a link or pointer to the next node. This representation is called a one way chain or singly linked list and it can displayed simply as shown below. A)   ………  B)    2000 2010 2002 2012 C) INSERT NODE X   2000 2010 2002 2012 2100 D) DELETE NODE C    2000 2010 2002 2012 A 2010 B 2002 C 2012 E A 2100 B 2002 C 2012 E X 2010 A 2010 B 2012 E
  • 33. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 33 In figure (A) the variable first contains the address or pointer which gives the location of the first node of the list. Each node is divided in to two parts. The first part represent the information of the element and the second part contains the address of the next node. The last node of the list does not have a successor node and consequently no actual address is stored in the pointer field. In such case, a null value is stored as address. For Example, the linked list in fig(B) represents a 4 nodes units whose elements are located in memory locations 2000,2010,2002 and 2012 respectively . The linked address of NULL in the last node signals the end of the list. OPERATIONS 1. INSERTION 2. DELETION An insertion is performed in a straight forward manner. If a new element is to be inserted following the first element, this can be accomplished by merely interchanging pointers. For example, this can be shown in fig(C) for a 4 th element. The deletion of the fourth element from the original list can be performed by using the pointer change as shown in figure(D). It is clear that the insertion and deletion operations are more efficient when performed on linked list than an sequentially allocated list. OPERATIONS ON LINEAR LIST USING SINGLY LINKED LIST STORAGE A typical element or node consists of two fields namely an information field called INFO and a pointer field denoted by LINK. The name of a typical element is denoted by NODE. Pictorially , the NODE structure is as follows INFO LINK NODE It is further assumed that an available area of storage for this node structure consists of a linked state of available nodes as shown in Fig(A). TYPES OF LINKED LIST 1. INTERNAL ADDRESS 2. EXTERNAL ADDRESS 3. NULL ADDRESS
  • 34. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 34 FUNCTION INSERT (X,FIRST) Given X, a new element and first a pointer to the first element of a linked linear list whose typical node contains INFO & LINK field as previously discussed. This function inserts X. AVAIL is a pointer to the top element of the availability stack. NEW is a temporary pointer variable. It is required that X proceed the node whose address is given by FIRST. 1. [UNDERFLOW] IF AVAIL= NULL THEN WRITE (AVAILIABILITY STACK UNDERFLOW) RETURN[FIRST] 2. [OBTAIN ADDRESS OF NEXT FREE NODE] NEW AVAIL 3. [REMOVE FREE NODE FROM AVAILIABILITY STACK] AVAIL LINK(AVAIL) 4. [INITIALIZE FIELDS OF NEW NODE AND ITS LINK TO LIST] INFO(NEW) X LINK(NEW)FIRST 5. [RETURN ADDRESS OF NEW NODE] RETURN (NEW) FUNCTION INSERT END (X, FIRST) 1. [UNDERFLOW] IF AVAIL=NULL THEN WRITE (AVILABILITY STACK UNDERFLOW) RETURN (FIRST) 2. [OBTAIN ADDRESS OF NEXT FREE NODE] NEW AVAIL 3. [REMOVE FREE NODE FROM AVAILABILITY STACK] AVAILLINK(AVAIL) 4. [INITIALIZE FIELDS OF NEW NODE] INFO(NEW)X LINK(NEW)NULL 5. [IS THE LIST EMPTY] IF FIRST =NULL THEN RETURN (NEW) 6. [INITIATE SEARCH FOR LAST NODE] SAVE FIRST 7. [SEARCH FOR END OF LIST] REPEAT WHILE LINK(SAVE)≠ NULL SAVE LINK(SAVE) 8. [SET LINK FIELD OF LIST NODEE TO END] LINK(SAVE)NEW
  • 35. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 35 9. [RETURN FIRST NODE POINTER] RETURN (FIRST) DELETING A NODE FUNCTION DELETE(X,FIRST) 1. [EMPTY LIST] IF FIRST= NULL THEN WRITE (UNDERFLOW) RETURN 2. [INITIALIZS SEARCH FOR X] TEMP FIRST 3. [FIND X] REPEAT THROUGH STEP-5 WHILE TEMP≠ X AND LINK(TEMP) ≠ NULL 4. [UPDATE PREDECESSOR MARKER] PRED TEMP 5. [MOVE TO NEXT NODE] TEMPLINK[TEMP] 6. [END OF THE LIST] IF TEMP ≠ X THEN WRITE(NODE NOT FOUND) RETURN 7. [DELETE X] IF X= FIRST [IS X THE FIRST NODE] THEN FIRST<LINK(FIRST) ELSE LINK(PRED)LINK(X) 8. [RETURN NODE TO AVAILABILITY AREA] LINK(X)AVAIL AVAILX RETURN COPY A NODE A General algorithm to copy a linked list is now presented. 1. [EMPTY LIST] IF FIRST=NULL THEN RETURN [NULL] 2. [COPY FIRST NODE] IF AVAIL =NULL THEN WRITE (AVAILABILITY STACK UNDERFLOW) RETURN (0) ELSE NEWAVAIL AVAILLINK(AVAIL)
  • 36. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 36 FIELDINFO(FIRST) BEGINNEW 3. [INITIALIZE TRAVERSAL] SAVEFIRST 4. [MOVE TO NEXT NODE IF NO AT THE END OF LIST] REPEAT THROUGH STEP-6 WHILE LINK[SAVE] ≠NULL 5. [UPDATE PREDECESSOR AND SAVE POINTERS] PREDNEW SAVELINK(SAVE) 6. [COPY NODE] IF AVAIL= NULL THEN WRITE(AVAILABILITY STACK UNDERFLOW) RETURN (0) ELSE NEWAVAIL AVAILLINK(AVAIL) FIELD(NEW)INFO(SAVE) PTR(PRED)NEW 7. [SET LINK OF LAST NODE AND RETURN] PTR(NEW)NULL RETURN(BEGIN) POLYNOMIAL A node consists of number of fields each of which can represent an int , a real number etc..except for one field called the pointer which contains the location of the next node in the list. Consider the example of representing a term of a polynomial in the variables x,y,z a typical node is represented as follows. Power-x Power-y Power-z Co-efficien LINK TERM Which consists of 5 sequentially allocated fields, that we collectively refer to ‘TERM’. The first three fields represent the power of the variables x,y and z respectively. The 4 th and 5 th field represent the co efficient of the ‘TERM’ in the polynomial and the address of the next in the polynomial respectively. For example the term 3xy would be represented in the figure, 1 1 0 3
  • 37. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 37 This selection of a particular field with in a node for a polynomial example in an easy matter.Our algorithm notation allows the referring of any field of a node given the pointer p to the node. Co-eff(p) denotes the coefficient field of the node pointed to by P. similarly the exponent of x,y,z are given by power x(p),power y(p) and power z(p) respectively and the pointer to the next node is given by LINK(P). Consider as an ex, the representation of the polynomial 2x2 +5xy+y2 +yz as a linked list. Assuming that the nodes in the list are to be stored such the term pointer to by p, proceeds another term indicated by Q, if power x(P) is greater than power x(Q) or if the powers of x are equal, then power y(p) ,must be equal than power y(Q) or if the power of y are equal then power z(p) must be greater than power z(Q). For example, the list is represented by the following figure,( 2x2 +5xy+y2 +yz) X y z co-eff 2 0 0 2 2x2 1 1 0 5 5xy 0 2 0 1 Y2 0 1 1 1 Yz OPERATION ON POLYNOMIAL INSERTION FUNCTION POLY FRONT (NX,NY,NZ,NCOEFF,POLY) Given the definition of the node structure TERM under availability area from which we can obtain such nodes, it is required to insert a node in the linked list so that it immediately preceeds the node whose address is designated by the pointer POLY. The fields of the new term are denoted by NX,NY,NZ,NCOEFF which corresponds to the exponents for x,y,z and the co- efficient value of the term respectively, NEW is a pointer variable which contains the address of the new node. 1. [OBTAIN A NODE FROM AVAILABLE STORAGE] NEWTERM 2. [INITIALIZE NUMERIC FIELDS]
  • 38. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 38 POWER-X (NEW)NX POWER-Y(NEW)NY POWER-Z(NEW)NZ COEFF(NEW)NCOEFF 3. [SET LINK TO THE LIST] LINK[NEW]POLY 4. [RETURN FIRST NODE POINTER] RETURN [NEW] EXAMPLE :YZ+Y2 +5XY+2X2 1. POLY 0 1 1 1 2. POLY 0 2 0 1 0 1 1 1 3. POLY 1 1 0 5 0 2 0 1 0 1 1 1 - 4. POLY 2 0 0 2 1 1 0 5 0 2 0 1 0 1 1 1 - FUNCTION POLYEND (NX,NY,NZ,N,COEFF,POLY) Given the definition of the node structure TERM under availability area from which we can obtain such node is referred to insert a node in the , list so that it immediately proceeds the node whose address is designated by the pointer POLY. The fields of the new TERM are denoted by NX,NY,NZ,NCOEFF Which corresponds to the exponents for x,y,z and the co efficient value of the term respectively. NEW is a pointer variable which contains the address of new node. SAVE is a temporary pointer variable. 1. [OBTAIN A NODE FROM AVALIABLE STORAGE] NEW TERM 2. [INITIALIZE NUMERIC FIELDS] POWER X(NEW)NX POWER Y(NEW)NY POWER Z(NEW)NZ
  • 39. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 39 3. [IS THE LIST EMPTY] IF POLY=NULL THEN RETURN[NEW] 4. [INITIATE SEARCH FOR LAST NODE] SAVEPOLY 5. [SEARCH FOR END OF LIST] REPEAT WHILE LINK(SAVE) ≠ NULL SAVELINK(SAVE) 6. [SET LINK FIELD OF LAST NODE TO NEW] LINK(SAVE)NEW 7. [RETURN FIRST NODE POINTER] 8. RETURN(POLY) EXAMPLE :2X2 +5XY+Y+YZ 1. POLY 2 0 0 2 2. POLY 2 0 0 2 1 1 0 5 3. POLY 2 0 0 2 1 1 0 5 0 2 0 1 - 4. POLY 2 0 0 2 1 1 0 5 0 2 0 1 0 1 1 1 - POLYLAST(NX,NY,NZ,NCOEFF,POLY) Given the definition of the node structure TERM under availability area from which we can obtain such nodes, it is required to insert a node in a linked list. So that it immediately proceeds the node whose address is designated by the pointer POLY. The global pointer variable LAST denotes the address of the last node in the list. The fields of the new term are denoted by NX,NY,NZ,NCOEFF, which corresponds to the term respectively NEW is a pointer variable which contains the address of the new node. 1. [OBTAIN A NODE FROM AVAILABLE STORAGE] NEWTERM 2. [INITIALIZE NUMERIC FIELDS]
  • 40. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 40 POWER X(NEW)NX POWER Y(NEW)NY POWER Z(NEW)NZ CO-EFF(NEW)NCOEFF LINK(NEW)NULL 3. [IS THE LIST EMPTY] IF POLY = NULL THEN LASTNEW RETURN(NEW) 4. [INSERT NODE IN NON EMPTY LIST] LINK(LAST)NEW LASTNEW POLYNOMIAL ADDTION A general algorithm for adding two polynomial is presented. FUNCTION POLY ADD(P,Q) Given two polynomial whose first terms are referred by pointer variables P & Q respectively, and insertion function as described in function copy, is required to add their polynomials and score their sum in a third polynomial which is referenced by the pointer variable R. The original polynomials are to remain unchanged. PSAVE & QSAVE are pointer variables. A1,A2,B1,B2,C1,C2,D1 & D2 are temporary variables of global variables. 1. [INITIALIZE] RNULL PSAVEP QSAVEQ 2. [END OF ANY POLYNOMIAL] REPEAT THROUGH STEP4 WHILE P ≠ NULL AND Q ≠ NULL 3. [GET VALUES FOR EACH THEM] A1POWER X(P) A2POWER X(Q) B1POWER Y(P) B2POWER Y(Q) C1POWER Z(P) C2POWER Z(Q) D1 COEFF(P) D2COEFF(Q) 4. [COMPARE TERMS]
  • 41. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 41 IF (A1=A2)AND(B1=B2)AND(C1=C2) THEN IF D1+D2 ≠0 THEN RPOLYLAST(A1,B1,C1,D1+D2,R) PLINK(P) QLINK(Q) ELSEIF[(A1>A2)OR(A1=A2)AND(B1>B2)] OR[(A1=A2)AND(B1=B2)AND(C1>C2)] THEN RPOLYLAST(A2,B2,C1,D1,R) PLINK(P) ELSE RPOLYLAST(A2,B2,C2,D2,R) QLINK(Q) 5. [NOT AT END OF ONE OF THE POLYNOMIAL] IF P ≠ NULL THEN LINK(LAST)COPY(P) ELSE IF Q≠NULL THEN LINK(LAST)COPY(Q) 6. [RESTORE INITIAL POINTER VALUES FOR P & Q] PPSAVE QQSAVE 7. [RETURN POINTER TO SUM POLYNOMIAL] RETURN(R) DOUBLY LINKED LINEAR LIST Linked linear list implies that each node must contain two link fields instead of the usual one. The links are used to denote the predecessor and successor of a node. The link denoting the predecessor of a node is called the left link containing this type of node is called doubly linked linear list or a two way chain. L R Where L and R are pointer variables denoting the left most and right most nodes in the list respectively. The left link of the leftmost and the right link of the rightmost node are both NULL, indicating the end of the list for each direction. The left and right link of a node are denoted by the variables LPTR and RPTR respectively. PROCEDURE FOR DOUB INS(L,R,M,X) Given a doubly linked linear list whose leftmost and rightmost node address are given by the pointer variable L and R respectively. It is required to insert a node whose address is given by pointer variable P. The right and left link of node are denoted by LPTR and RPTR. The
  • 42. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 42 information field of a node denoted by the variable M. The information is to entered in the node is contained in X. CREATION OF LINK 1. PROCEDURE DOUBLE INSERT (L,R,M,X) 2. GETNODE (P) 3. INFO(P)X 4. IF R=NULL THEN LPTR(P)RPTR(P)NULL 5. RETURN INSERTION OF FIRST NODE 1. GETNODE(P) 2. INFO (P)X 3. IF M=L THEN LPTR (P)NULL RPTR(P)M LPTR(M)P RETURN INSERTION TO MIDDLE 1. GETNODE (P) 2. INFO(P) 3. LPTR(P)LPTR(M) 4. RPTR(P)M 5. LPTR(M)P INSERTION TO LAST NODE 1. GETNODE(P) 2. INFO(P)X 3. RPTR(M)P 4. LPTR(P)M 5. RPTR(P)NULL LPTR INFO RPTR LPTR INFO RPTR LPTR INFO
  • 43. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 43 PROCEDURE DOUB DEL(L,R,OLD) Given a doubly linked list, get the address of the leftmost and right most nodes given by the pointer variable L &R respectively. It is required to delete the node whose address is containedin the variable OLD. Nodes contain left and right links with names LPTR and RPTR respectively. PROCEDURE DOUB DEL(L,R,OLD) 1. UNDERFLOW IF R=NULL THEN WRITE(UNDERFLOW) RETURN 2. DELETE NODE (ONE NODE,L,R) IF L=R THEN LRNULL RETURN 3. DELETE NODE(FIRST NODE] IF OLD=L THEN LRPTR(L) LPTRNULL (OR)RETURN(OLD) FREENODE(OLD) 4. LAST NODE IF OLD=R THEN RLPTR (R) RPTR (R )NULL FREENODE(OLD)
  • 44. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 44 UNIT-IV GRAPHS DEFINITION OF GRAPH A graph G consist of a non-empty set V called the set of nodes(points, vertices) of the graph, a set E which is the set of edges of the graph and a mapping from the set of edges to a set of pair of elements of v. A Graph defined as G=(V,E). V2 E1 E2 V1 V3 E4 E3 V4 In this V1,V2,V3,V4 are set of nodes and E1,E2,E3,E4 are set of edges. ADJACENT NODE Any two nodes which are connected by an edge in a graph are called adjacent node. V1 E V2 V1 and V2 are adjacent node which are connected by an edge E in a graph. DIRECTED EDGE Graph G is equal to (V,E) an edge which is directed from one node to another is called a directed Edge. V1 E V2
  • 45. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 45 UNDIRECTED EDGE An edge which has no specific direction is called an undirected edge. V1 E V2 There is an no specific direction. So it is undirected graph. TYPE OF GRAPHS DIRECTED GRAPH A Graph In Which Every Edge Is Directed is called a directed graph (or) Dia graph (or) Di graph. V2 E1 E2 V1 V3 E4 E3 V4 UNDIRECTED GRAPH A Graph in which every edge is undirected is called an undirected graph. V2 E1 E2 V1 V3 E4 E3 V4
  • 46. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 46 MIXED GRAPH Some of the edges are directed and some of the edges are undirected in a graph, then the graph is a mixed graph. V2 E1 E2 V1 V3 E4 E3 V4 INITIATING AND TERMINATING Pair of node (U,V) then the edge x is said to be initiating is the node U and terminating Or ending is the node V. The nodes U and V are also called the initial and terminal nodes of the edge x. U V LOOP An edge of a graph, which join a node itself is called a loop. V2 E1 E2 V1 V3 E4 E3 V4
  • 47. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 47 PARALLEL GRAPH Certain pair of nodes joined by more than one edge, such edges are called parallel graph. V2 E1 E2 V1 V3 E4 E3 V4 MULTI GRAPH Any graph which contain some parallel edges is called a multi graph. V2 E1 E2 V1 V3 E4 E3 V4 SIMPLE GRAPH No more than one directed edge in the case of a directed graph such a graph is called a simple graph.
  • 48. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 48 WEIGHTED GRAPH A Graph in which weights are assigned to every edge is called a weighted graph. 5 20 10 V3 30 40 ISOLATED GRAPH A node which is not adjacent to any other node is called an isolated node 2 1 5 6 6 3 4 HERE 6 IS AN ISOLATED GRAPH NULL GRAPH A Graph containing only isolated nodes is called a null graph. V2 V1 V3 V4
  • 49. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 49 IN DEGREE, OUT DEGREE AND TOTAL DEGREE In a directed graph for any node, the number of edges which have U as their initial node is called the Out Degree of the nodes. The number of edges which have V as their terminal node is called IN DEGREE of V and the sum of the out degree and in degree of a node is called TOTAL DEGREE. EXAMPLE 1: 1 3 2 IN DEGREE=1 , OUT DEGREE=2, TOTAL DEGREE=3 EXAMPLE 2: Here e2 and e4 are the out degree, e1 is the in degree. PATH A Path is said to traverse through the nodes appearing in the sequence, originating in the initial node of the first edge and ending in the terminal node of the last edge in the sequence. V1 V2 V4 V3
  • 50. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 50 V1V2V3V4 V1V2V4 V1V3V4 V1V4 LENGTH The number of edges appearing in the sequence of a path is called the length of the path. V1 V2 V4 V3 V1V2V3V4 =3 V1V2V4 =2 V1V3V4 =2 V1V4 =1 CYCLIC A path which originate and ends in the same node is called a cyclic. ACYCLIC A Simple diagraph which does not have any cyclic is called Acyclic. DIRECTED TREE A Directed tree is an acyclic diagraph which has one node called its root. An isolated node is called a directed tree. In a directed tree any node which has out degree 0 is called a terminal node or leaf. An other node are called branch node.
  • 51. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 51 STRONGLY CONNECTED GRAPH A Diagraph is called strongly connected if there is a directed path from any vertex to any other vertex. WEEKLY CONNECTED GRAPH There does not exist a directed path from vertex, one to vertex 4, also from vertex 5 to other vertex. It is called a weekly connected graph. A special type of graph is called tree. A graph is a tree if it has two properties. 1. It is connected 2. There are no cycles in a graph. EXAMPLES 1 2 3 4 5 A B C D 1 2 3 4 5 1 2 3 4 5 6 7
  • 52. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 52 GRAPH REPRESENTATION Two such representations are commonly used there are, 1. Adjacent matrix 2. Adjacent list representation The choice of representation depends on the application and function to be performed on the graph. ADJACENT MATRIX A Adjacent matrix A for a graph g=(V,E) with n vertices, is an n cross n matrix of bits, Such that A(i,j)=1, iff there is no such edge. The figure shows the adjacent matrix the graph shown in figure. The total number of 1’s accounts for the number of edges in the diagraph. The number of 1’s in each row tells the out degree of corresponding vertex. The adjacent matrix is a simple way to represent a graph but it has two disadvantages. 1. It take1s O(n2 ) space to represent a graph with n vertices even for sparse graph and 2. It takes (n2 ) time to save most of the graph problems. Vertex 1 2 3 4 5 1 0 1 1 0 0 2 0 0 1 0 0 3 0 0 0 1 0 4 0 0 0 0 0 5 1 0 1 1 0 1 5 4 3 2
  • 53. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 53 ADJACENCY LIST REPRESENTAION In this representation we score a graph as a linked structure, We score all the vertices in a list and then for each vertex, we have a linked list of its adjacent vertices. EXAMPLE V6 V5 V4 V2 V3 V1 V1 V1
  • 54. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 54 UNIT – V TREES DEFINITION OF TREE Usually, draw trees with a root at the top. Each node has exactly one node about it which is called its parent. A node directly below a node is called a children. TREE RELATED TERMS A Tree is a non-empty collection of vertices and edges that satisfy certain requirements. A vertex is a simple object (node) that can have a name and carry other associated information. An edge is a connection between two vertices. A tree may, therefore, be defined as a finite set of one or more vertices such that, 1. There is a one specially designated vertex called root. 2. The remaining vertices are partitioned in to collection of subtree, with each of which is also a tree. FOREST TREE A Set of trees is called a forest tree. EXAMPLE A B C D G F E H I J K L M
  • 55. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 55 PROPERTIES OF A TREE 1. Any node can be root of the tree and each node in the tree has the property that there is exactly one path connecting that node with every other node in the tree. 2. Each node, except the root has a unique parent and every edge connects a node to its parent. A tree worth N nodes has N-1 edges. BINARY TREES A Binary tree is a tree which is either empty or consists of a root node and two disjoint binary trees called left sub tree and right sub tree. In figure a binary tree is depicted with a left sub tree L(T) and the right sub tree is denoted by R(T).In a binary tree no node can have more than two children, or two node. PROPERTIES OF BINARY TREE 1. A Binary tree with N internal node have maximum of N+1 external node. Root is considered as an external node. 2. The external path, length of any binary tree with a internal node is 2n >the internal path length. 3. The height of full binary tree with N internal node is above log2 N. FULL BINARY TREE A Full binary tree or a complete binary tree is a binary tree in which all internal nodes have degree and all leaves are at the same level. EXAMPLE LEVEL 1 LEVEL2 LEVEL3 1 2 3 4 5 6 7 1 2 3 4 5 6 7
  • 56. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 56 TREE REPRESENTATION 1. VENN DIAGRAM 2. NESTING PARANTHESIS 3. TEBLE OF CONTENTS 4. LEVEL NUMBER FORMAT EXAMPLE VENN DIAGRAM NESTING PARANTHESIS (V0(V7(V8)(V9(V10)))(V1(V2(V5)(V6))(V3)(V4))) V0 V1 V7 V3 V9 V8 V4 V10 V5 V2 V6
  • 57. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 57 TABLE OF CONTENTS VO -------------------------------------------- V1-------------------------------------------- V2----------------------------------------- V5------------------------------------- V6----------------------------------- V3------------------------------------------- V4-------------------------------------------- V7---------------------------------------------- V8------------------------------------------ V9------------------------------------------- V10--------------------------------------- LEVEL NUMBER FORMAT 1. VO -------------------------------------------- 2. V1-------------------------------------------- 3. V2----------------------------------------- 4. V5------------------------------------- 4. V6----------------------------------- 3. V3------------------------------------------- 3. V4-------------------------------------------- 2. V7---------------------------------------------- 3. V8------------------------------------------ 3. V9------------------------------------------- 4. V10---------------------------------------
  • 58. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 58 CONVERSION OF BINARY TREE A forest tree can also be represented by a binary tree. The two stages to obtain a binary tree which represents a given ordered tree is as follows. As a first step, we delete all the left most branch. Also we draw edges from a node to the node on the immediate right, if any, which is situated at the same level. Once this is done, then for any particular node we choose its left and right children in the following manner. The left child is the node and the right child is the node to the immediate right of the given node on the same horizontal line. Such a binary tree will not have a right subtree. GENERAL TREE TO BINARY TREE GIVEN DIRECTED TREE STAGE 1 a b f c d g j k e h i
  • 59. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 59 STAGE 2 FOREST TO BINARY TREE STAGE 1
  • 60. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 60 STAGE 2 OPERATION S ON BINARY TREE [TREE TRAVERSAL] One of the most common operations performed on tree structure is that of traversal. This is a procedure by which each node in the tree is processed exactly once in a systematic manner. There are three main ways of traversing a binary tree. 1. PREORDER 2. INORDER 3. POSTORDER The preorder traversal of a binary tree is defined as follows, 1. Process the root node 2. Traverse the left subtree in preorder 3. Traverse the right subtree in preorder EXAMPLE A B D C E G F ANS: ABCDEFG
  • 61. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 61 The inorder traversal of a binary tree is given by the following steps, 1. Traverse the left subtree in preorder 2. Process the root node 3. Traverse the right subtree in preorder EXAMPLE A B D C E G F ANS: CBAEFDG Finally, we define the post order traversal of a binary tree as follows, 1. Traverse the left subtree in preorder 2. Traverse the right subtree in preorder 3. Process the root node EXAMPLE A B D C E G F ANS: CBFEGDA
  • 62. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 62 NON-RECURSIVE MANNER PROCEDURE FOR PREORDER 1. [INITIALIZE] IF T=NULL THEN WRITE(EMPTY TREE) RETURN ELSE TOP0 CALL PUSH(S,TOP,T) 2. [PROCESS EACH STACKED BRANCH ADDRESS] REPEAT STEP 3 WHILE TOP >0 3. [GET STORED ADDRESS AND BRANCH LEFT] PPOP(S,TOP) REPEAT WHILE P≠ NULL WRITE (DATA(P)) IF RPTR(P) ≠NULL THEN CALL PUSH(S,TOP,RPTR(P)) PLPTR(P) 4. [FINISHED] RETURN PROCEDURE FOR POST ORDER 1. [INITIALIZE] IF T=NULL THEN WRITE(EMPTY TREE) RETURN ELSE PT TOP0 2. [TRAVERSA IN POSTORDER] REPEAT THROUGH STEP 5 WHILE TRUE 3. [DESCEND LEFT] REPEAT WHILE P≠NULL CALL PUSH(S,TOP,P) PLPTR(P) 4. [PROCESS A NODE WHOSE LEFT AND RIGHT SUBTREE HAVE BEEN TRAVERSED] REPEAT WHILE S[TOP]<0 PPOP(S,TOP) WRITE(DATA(P)) IF TOP=0
  • 63. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 63 THEN RETURN 5. [BRANCH RIGHT AND THEN MARK NODE FROM WHICH WE BRANCHED] PRPTR(S[TOP]) S[TOP]S[TOP] RECURSIVELY MANNER PROCEDURE FOR INORDER 1. [CHECK FOR EMPTY TREE] IF T=NULL THEN WRITE(EMPTY TREE) RETURN 2. [PROCESS THE LEFT SUBTREE] IF LPTR(T) ≠NULL THEN CALL POSTORDER(LPTR(T)) 3. [PROCESS THE RIGHT SUB TREE] IF RPTR(T) ≠NULL THEN CALL POSTORDER(RPTR(T)) 4. [PROCESS THE ROOT NODE] WRITE(DATA(T)) 5. [FINISHED] RETURN GRAPH TRAVERSAL 1. BFS: QUEUEBREADTH FIRST SEARCH 2. DFS:STACKDEPTH FIRST SEARCH PROCEDURE BFS(INDEX,LINK,QUEUE) REACHspecifies whether the node has been reached in the traversal and its initial value is false. NODE NO Identifies the node number DATAcontain a information of control DISTANCEIt is the variable which contains a distance from the start node. LIST PTRIt is a pointer to a list of adjacent edge for the node. DEST INContains the number of terminal nodes for this edge. EDGEPPTRPoints to the next edge in the list.
  • 64. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 64 ALGORITHM 1. [INITIALIZE] REACH[INDEX]TRUE DIST[INDEX]0 CALL QINSERT(QUEUE,INDEX) 2. [REPEAT UNTILL ALL NODE HAVE BEEN EXAMINED] REPEAT THROUGH STEP-5 WHILE QUEUE IS NOT EMPTY. 3. [REMOVE THE CURRENT NODE TO THE EXAMINE FROM THE QUEUE] CALL QDELETE(QUEUE,INDEX) 4. [FIND ALL UNABLE NODES ADJACENT TO CURRENT NODE] LINKLIST PTR(INDEX) REPEAT STEP-5 WHILE LINK ≠ NULL 5. [IS THIS A UNVISITED NODE LABEL IT AND ADDING IT IN A QUEUE] IF NOT REACHED[DEST IN[LINK]] THEN REACH [DEST IN[LINK]]DIST[INDEX] CALL QINSERT(QUEUE,DEST IN (LINK)) LINKEDGE PTR(LINK) 6. [FINISHED] RETURN NOTE INDEXCurrent node being processed LINKPoint to the edge being examined QUEUEDenote the name of the QUEUE DIAGRAM REPRESENTATION 200 Mumbai 1300 Chennai 900 780 Delhi Hyderabad 1400 600 160 Luck now 800 Calcutta Bangalore 1 2 5 4 3 7 6
  • 65. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 65 REACH NODE DATA DIST LINK(P) DEST IN EDGE PTR True 1 Chennai 0 2 6 True 2 Bombay 200 5 4 True 3 Delhi 600 2 7 True 4 Hyderabad 780 7 5 True 5 Luck now 900 4 1 True 6 Bangalore 160 7 1 True 7 Calcutta 800 6 3 DEPTH FIRST SEARCH PROCEDURE DFS(INDEX,COUNT) Given the structure as described before, this recursive procedure calculates the depth first search numbers for a graph. INDEX is the current index into the node table directory table and is assumed to be initialized to one outside the procedure COUNT is used to keep track of the current DFN node number and is initially set to zero outside the procedure. Finally, it is assumed the DFN field as initialized to zero when the adjacency list structure was created. ALGORITHM 1. [UPDATE THE DEPTH FIRST SEARCH NUMBER SET AND MARK CURRENT NODE] COUNTCOUNT+1 DFS[INDEX[COUNT REACH[INDEX]TRUE 2. [SETUP LOOP TO EXAMINE EACH NEIGHBOUR OF CURRENT NODE] LINKLIST PTR[INDEX] REPEAT STEP 3 WHILE LINK ≠ NULL 3. [IF NODE HAS NOT BEEN MARKED,LABEL IT AND MAKE RECURSION CALL] IF NOT REACH[DESIGN (LINK)] THEN CALL DFS(DESTIN(LINK), COUNT) LINK EDGE PTR(LINK) 4. [RETURN TO POINT OF CALL] RETURN
  • 66. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 66 DIAGRAM REPRESENTATION 1 3 2 6 5 4 HASHING A function is a small task, that execute particular statement block. The function has two uses. 1. The result of the function is used as a kind of key in which the list is stored (i.e) the function is used to determine where is the array to store the record. 2. Function is used as a method of ascending the record. This function is called HASH function. Hash Function = key mod 100 The remainder is used as an index in to array of employee records. Example: (00) (01) Key (02) 459250704 key mod 10024 (99) COLLISIONS The same address will occur that is called collisions. Resolving collision techniques 1. Hash and search 2. Rehashing 3. Chaining C A B D E F Hash function
  • 67. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 67 1. HASH AND SEARCH A Simple approach to resolving collision is to store the colliding element to next available space. Key 556677003 00 01 02 03 04 Try index 3 REHASHING Another common technique for resolving collision is rehashing. If the first computation of the hash function produce a collision, we can use hash address as the input to the rehash function and computes new address. Original hash function = key MOD 100 Rehash function = (key+1) MOD 100 Until find the empty address. CHAINING OR BUCKET OR LIST METHOD A third technique for handling collisions was the hash address not as the actual location of the record, but as the index in to an array of pointers called buckets. Each bucket points to a linked list or chain of records that share the same hash address. 00 01 02 09 H.P Empty 02 12345003 04
  • 68. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 68 HASHING RECHNIQUES 1. MID SQUARE METHOD The key is multiplied by itself , and the central digits of the square are taken and adjusted to fit the range of addresses. Thus , if the record have 6-digits key and 1000 buckets are used , the key may be squared to form a 12-digits field of which digits 5 to 8 are used. Thus if the key is 172148, the square is 02963493304. The central four digits are multiplied by 0.7 : 3493 * 0.7 = 2445. The 2445 is used as the bucket address.This is close to roulette-wheel randomization and the result are usually found to the close to the theoretical result of figure. 2 24 2 12 - 0 2 6 - 0 2 3 - 0 2 1 - 1 ADDRESS = 00011 2. DIVIDING It is possible to find a method which gives better results than a random number generator. A simple division method is such, the key is divided by a number approximately equal to the number of available addresses, and the remainder is taken as the relative bucket address, as in fig. A prime number or number with small factors is used. Thus if the key is 172148 again, and there are 7000 buckets, 172148 might be divided by 6997. The remainder is 4220, and this is taken as the relative bucket address. One reason division tends to give fewer overflows than a randomizing algorithm is that many key set have tons of consecutive numbers, there by distributing. 3. SHIFTING The outer digits of the key at both ends are record to overlap by an amount equal to the address length, as shown in figure. The digits are then added, and the result is adjusted to fit the range of bucket address.
  • 69. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 69 EXAMPLE 1 7 2 0 7 3 5 9 4. FOLDING Digits in the key are folded inward like folding papers as shown in figure . The digits are then added and adjusted as before. Folding tends to be more appropriate for large keys. EXAMPLE 1 7 2 0 7 3 5 9 5. DIGIT ANALYSIS Some attempts at achieving an even spread of bucket addresses have analyzed the distribution of values of each digit or character in the key. Those positions having the most skewed distribution are deleted from the key in the hope that any transform applied to the other digits will have a better chance of giving a uniform spread. 6. RADIX CONVERSION The radix of a number may be converted for example to radix 11. The excess high order digits may then be truncated. The key 172148 is converted to 1 * 115 +7*114 +2*113 +1*112 +4*111 +3*110 = 266373 and the digits 6763 are multiplied by 0.7 to give the relative bucket address 4461. Radix 11 conversion can be performed more quickly in a computer y a series of shifts and additions.
  • 70. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 70 7. LIN’S METHOD[Q] In this method a key is expressed in radix p, and the result is taken modulo qm , where p and q are prime number (or numbers without small prime factors) and m is positive integer. The key 172148 would first be written as a binary string:0001 0111 0010 0001 0100 1000. Grouping the string in to group of three bits, we obtain 000 101 110 010 000 101 001 000 = 05610510. This is expressed as a decimal number and divided by a constant qm . The remainder is used to obtain the relative bucket address. 8. POLYNOMIAL DIVISION Each digit of the key is regarded as a polynomial co-efficient, Thus the key 172148 is regarded as x5 +7x+4 +2x3 +x2 +4x1 +8x+0 . The polynomial so obtained is divided by another unchanging polynomial. The co efficient in the remainder forms the basis of the relative bucket address(x=2 or x=3). SHORTEST PATH PROBLEM DIJIKSTRA ALGORITHM We have seen in the graph traversals that we can travel through edges of the graph. It is very much likely in applications that these edges have some weights attached to it. They weight may reflect distance time or some other quantity that corresponds to the cost we incur when we travel through that edge. For example, in the graph in figure, we can go from Delhi to Andaman Nicobar through Madras of a cost of 7 or through Calcutta at a cost of 5. In these and many other applications we are often required to find a shortest path, i.e a path having the minimum weights between of finding shortest path for directed graph in which every edge has a non negative weight attached. 1 2 4 3 Let us at this stage recall how do we define a path . A path in a graph is sequences of vertices such that there is an edge that we can follow between each consecutive pair of vertices length of the path is the sum of weights of the edges of the path . The starting vertex of the path DELHI CALCUTTA MADRAS ANDAMAN
  • 71. DATASTRUCTURE (CS &CA) SIVASANKARI A Page 71 is called the source vertex and the last vertex of the path is called the destination vertex. Shortest path from vertex V to vertex W is a path for which the sum of the weights of the arcs on edges on the path is minimum. Here we must note that the path that may lock longer if we see the number of edges and vertices visited, at times may be actually shorter cost wise. Also we have two kinds of problem in finding shortest path. One could be that we have single source vertex and we seek a shortest path from that source vertex V to every other vertex of the graph. It is called single source shortest path problem. Consider the weighted graph in figure with 8 nodes. WEIGHTED GRAPH 2 1 2 2 4 3 4 6 1 3 3 7 5 There are many paths from A to H Length of path AFDEH = 1+3+4+6= 14 Another path from A to H is ABCEH It’s length is 2+2+3+6= 13 ********************************ALL THE BEST******************************* A B D F C E G H A B D F C E G H