Vous êtes sur la page 1sur 75

UNIT I-LINEAR STRUCTURES

DATA STRUCTURES
UNIT I-LINEAR STRUCTURES
DATA STRUCTURES
Data structure is defined as a system of organizing related piece of information. It is the
specialized format for organizing and storing data.
Data Structures are the methods of representing a logical relationships between the
individual data element related to the solution of the given problem.
TYPES OF DATA STRUCTURES
Data Structures
Primitive data structure Non primitive data structure
Int Float Char inear DS Non inear DS
!rrays Stac" #ueue $rees %raphs Sets
Primitive Data structure - It is the basic data structure which can be directly operated by the
machine instruction.
Non Primitive Data structure - It emphasize on structuring of a group of homogenous or heterogeneous
data item.
Linear data structures - inear arrangements of elements in memory.
Non Linear Data structures - It represents hierarchical arrangements of elements.
ABSTRACT DATA TYPE
It is a user defined data type in which it performs a set of operation.
It is a mathematical abstraction how the set of operations is implemented.
&b'ects such as lists( sets and graphs along with their operations can be viewed as abstract
data type
Set !D$( we have such operations as union( intersection( size and complement.
Implementation of these operations is written once in a program( any other part of the
program that needs to perform an operation on the !D$ by calling the appropriate
function.
!"# $ DATA STRUCTURES )
UNIT I-LINEAR STRUCTURES
LIST ADT
ist is an ordered set of elements( the general form of the list is !)(!*(!+,,!n
!)First element of the list
!nast element of the list
nSize of the list
If the element at position I is !i( then it successor is !i-) and its predecessor is !i.).
%ARIOUS OPERATIONS PERFOR&ED ON LIST
). Insert/0(12 Insert element 0 after the position 1
*. Delete/023lement 0 is deleted
+. Find/024eturns the position of 0
5. Ne0t/i24eturns the position of its successor element i-)
1. Previous/i24eturns the position of its predecessor i.)
6. Print listContents of the list is displayed
7. 8a"e empty8a"es the list empty
ARRAY BASED I&PLE&ENTATION
!rray is a collection of specified number of data stored in a consecutive memory location.
If an array is dynamically allocated( an estimate of the ma0imum size of the list is re9uired.
It re9uires a high over estimate( which waste considerable space.
It allows Print ist and Find to be carried out in linear time
Find "th operation ta"es constant time.
:ut insertion and deletion are e0pensive( Inserting at position ; re9uires )
st
pushing the
entire array down one spot.
Deleting the )
st
element re9uires shifting all the elements in the list up one( worst case of
these operation is &/N2
!n average( half of the list needs to be moved for either operation so linear time is still
re9uired.
4unning time for insertion and deletion is so slow( ist size must be "nown in advance.
Simple arrays are generally not used to implement list.
!"# $ DATA STRUCTURES *
UNIT I-LINEAR STRUCTURES
a<;= a<)= a<*= a<+= a<5= a<1=
*; ); +; 5; 1; 6;
LIN'ED LIST I&PLE&ENTATION
$o avoid the cost of insertion and deletion need to ensure that the list is not stored
contiguously.
&therwise entire part of the list will need to be moved.
in"ed list consists of a series of structure( not ad'acent in memory.
3ach structure contains elements and pointer to a structure containing its successor called
as Ne0t Pointer.
ast cells Ne0t Pointer points to N>.
C Specifies that N> is ;
! Pointer variable is a variable that contains the address where some other data are stored.
If P is declared to be a pointer to a structure then value stored in P is interpreted as the
location in 88. Field of the structure can be accessed by PField Name( where field
name is the name of the field.
(ENERAL IDEA OF LL
LIN'ED LIST )IT* ACTUAL POINTER %ALUES
### +## ,- ..-
From the pictorial representations among 5 structures the ne0t pointer in the )
st
structure as a
value ?;;( indicates where the second structure is.
INSERTION IN TO A LIN'ED LIST
!"# $ DATA STRUCTURES
A A! A" A-
+
A +## A! nu// A" ..- A- ,-
UNIT I-LINEAR STRUCTURES
DELETION FRO& A LIST
$o e0ecute Print ist/2 or Find/( @ey2 we merely pass a pointer to the first element in the
list and then traverse the list by following the ne0t pointer.

Delete30ecuted in one pointer change
Insertobtaining a new cell from the system by using malloc call
TYPES OF LIN'ED LIST
Singly in"ed ist
Doubly in"ed ist
Circular in"ed ist
SIN(LY LIN'ED LIST
! Singly in"ed ist is a list in which each node /or2 structure contains only one lin" field
pointing to the ne0t node of the list. Aeader is in Position ; and a with a header representing
the list !)(!*,,!1
TYPE DECLARATION OF LIN'ED LIST0
!"# $ DATA STRUCTURES
Y
A A! A" A-
5
A A! A" A-
A A! A" A-
*eader
UNIT I-LINEAR STRUCTURES
BifndefCistCA
struct Node
typedef struct node DPtr$oNodeE
typedef Ptr$oNode istE
typredef Ptr$oNode PositionE
ist 8a"e3mpty/ist 2E
Int Is3mpty/ist 2E
Int Isast/Position P(ist 2E
PositionFind/3lement $ype F(ist 2E
Goid delete/3lement $ype F(ist 2E
Position FindPrevious/3lement $ype F(ist 2E
Goid Insert/3lement $ype F(ist (Position P2E
Goid deletelist/istl2E
Position Aeader/ist 2E
Position First/ist 2E
Position !dvance/Position P2E
3lement$ype 4etrieve/Position P2E
Bendif
Struct Node
H
3lement$ype 3lementE
Position Ne0tE
IE
ROUTINE TO C*EC' )*ET*ER T*E LIST IS E&PTY
!"# $ DATA STRUCTURES 1
int Isempty/ist 2 <4eturn $rue if is 3mpty=
H
return Ne0tJJNIE
I

Em1t2 /ist 3it4 *eader

L
*eader
UNIT I-LINEAR STRUCTURES
ROUTINE TO C*EC' )*ET*ER T*E CURRENT POSITION IS LAST

FIND ROUTINE
ROUTINE TO INSERT AN ELE&ENT IN T*E LIST
!"# $ DATA STRUCTURES
int Isast/position P(ist 2 <4eturn true if P is in ast position in ist (
Parameter is >nused=
H
return P ne0tJJN>
I
### -### "###
P Pne5t
6
Position Find/3lement type F( ist 2 <4eturn position of F in EN> if not
found=
H
Position PE
PJNe0tE
Khile/PLJN> MM P3lementLJF2
PJPNe0tE
return PE 6
I
);;; *;;; +;;;
P P7P Ne5t P
Goid Insert /3lement type F( ist ( Position P2
H
Position $mpcellE
$mpcellJmalloc/sizeof/struct node22E
If/$mpcelJJN>2
Fatal 3rror/N&ut of spaceO2E
$mpcell3lementJFE
$mpcellNe0tJPNe0tE
P.PNe0tJ$mpcellE
I
678
### -### "###
P
8## Tm1ce//

UNIT I-LINEAR STRUCTURES
ROUTINE TO FIND NE6T
DELETE ROUTINE FOR LIN'ED LIST
!"# $ DATA STRUCTURES 7
)1
AFTER INSERTIN( T*E ELE&ENT 678
### 8## -### "###
PNe5t

Position FindNe0t/int F(ist 2 <4eturns the position of its successor=
H
PJNe0tE
Khile/PNe0tLJN> MM P3lement LJF2
PJPNe0tE
return PNe0tE
I
67-#
### -### "###
L P P7PNe5t 6
UNIT I-LINEAR STRUCTURES
ROUTINE TO DELETE T*E LIST
!"# $ DATA STRUCTURES ?
Aeader *; null )1 *;;; ); )1;;
Goid delete /3lement $ype F(ist 2
H
Position P($mpcellE
PJFindPrevious/F(2
If /LIslast/P(22
H
$mpcellJPNe0tE
PNe0tJ$mpcellnet0E
free/$mpcell2E
I
I
Be9ore De/etion PNe5t 678
### 8## -###
P $mpcell

Goid Deletelist/ist 2
H
Position P( $mpcellE
PJNe0tE
Ne0tJN>
Khile/PLJN>2
H
$mpcellJPNe0tE
free/P2E
PJ$mpcellE
I
I
Ne0tJN>
);;; P *;;;
$mpcellJPNe0t
P $mpcell
free/P2
P
$mpcell(PJN>E
A9ter De/etion
### -###
UNIT I-LINEAR STRUCTURES
!"# $ DATA STRUCTURES Q
UNIT I-LINEAR STRUCTURES
DOUBLY LIN'ED LIST
! doubly in"ed ist is a list in which each structure or node has three fields namely data field(
forward lin" <Flin"=(:ac"ward in" <:lin"=. Flin" points to the successor node in the list ( where :lin"
points to the predecessor node.
Re1resentation o9 dou:/2 /in;ed /ist
Aeader
Ne0t Pointer
Node ) Node * Node +
Previous
Pointer
$he previous pointer is the :lin" which contains the address of the previous node( the ne0t pointer
is the Flin" which contains the address of the ne0t node.
P*YSICAL REPRESENTATION OF DOUBLY LIN'ED LIST
Node )
Node *
Node +
Data
Previous
Pointer
Ne0t
Pointer
!ddressJ);;
!ddressJ));
!ddressJ)*;
);
*;
+;
N>
);;
));
));
)*;
N>

STRUCTURE DECLARATION
Struct Node
H
int 3lementE
Struct Node DFlin"E
Struct Node D:lin"E
IE
!"# $ DATA STRUCTURES
BLIN' DATA POINTER FLIN'
);


# # ## -# -# # "# nu//
Aeader/);;2
UNIT I-LINEAR STRUCTURES
ROUTINE TO INSERT AN ELE&ENT IN A DOUBLY LIN'ED LIST
R
Insert an e/ement 8# a9ter t4e 1osition o9 e/ement # in a Lin;ed List
E5am1/e0 Ne3node is created 3it4 t4e e/ement 8#
)1;
Ne3nodeE/ement7678#
!"# $ DATA STRUCTURES ))
Goid Insert/int F(ist (Position P2
H
Struct Node DNewnodeE
NewnodeJmalloc/Sizeof/Struct Node22E
if/NewnodeLJN>2
H
Newnode3lementJFE
NewnodeFlin"JPFlin"E
PFlin":lin"JNewnodeE
PFlin"JNewnodeE
Newnode:lin"JPE
I
I
Insert an E/ement 8#

*eader
P );; )); )*;
)1;
FJ1;

B/in; Ne3node F/in;
1;
1;
UNIT I-LINEAR STRUCTURES
*ere t4e 1osition P is insert t4e ne3 e/ement a9ter P
##
P
Ne3nodeF/in;7PF/in;7#
PF/in;B/in;7Ne3mode78#
<#B/in;=
Ne3nodeB/in;7##
Aeader
Node ) Node + Node 5
);; )); )*;
Node *
)1;
AFTER INSERTION OF A LIS$
Aeader

Node) Node * Node + Node 5


P );; )1; )); )*;
!"# $ DATA STRUCTURES )*
# #
); )1; )); +; null )1; *; )*; );; 1; ));
)); +; null )1; *; )*;
);; 1; ));
); )1;

UNIT I-LINEAR STRUCTURES
ROUTINE TO DELETE AN ELE&ENT
Goid delete/int F(ist 2
H
position PE
PJFind/F(2E
If /islast /P(2
H
$empJPE
P:lin"Flin"JN>E
Free/$emp2E
I
else
H
$empJPE
P:lin"Flin"JPFlin"E
PFlin":lin"JP:lim"E
Free/$emp2E
I
I
Aeader

Node ) Node * Node + Node 5 P



);; )1; )); )*;
Delete an element in a doubly lin"ed list which is present at last in the list.
!ssign the last element position P as temp(assign Null to P:lin"flin" and delete the temp
!"# $ DATA STRUCTURES )+
); )1; )); +; null )1; *; )*; );; 1; ));
UNIT I-LINEAR STRUCTURES
Aeader

Node ) Node * Node +
);; )1; ));
Ot4er3ise de/ete an e/ement in t4e /ist 3it4 an2 1osition P>
Node ) Node * Node +
Aeader
);; )1; ));
Assi?n P as Tem1>
PB/in;F/in;71F/in;7#
Assi?n # to 1B/in;F/in;@PB/in;77##F/in;78#A
PF/in;B/in;7PB/in;7P7##
Assi?n ## to PF/in;B/in;@PF/in;7#B/in;78#A
AFTER DELETION
);; ));
AD%ANTA(E
Deletion operation is easier
Finding the Predecessor and Successor of node is easier
DISAD%ANTA(E
8ore memory space is re9uired since it has two pointer
!"# $ DATA STRUCTURES )5
); )1; )1; *; null );; 1; ));
); )1; )1; *; null );; 1; ));
); )); );; *; null
UNIT I-LINEAR STRUCTURES
CIRCULAR LIN'ED LIST
In a Circular in"ed ist the pointer of the last node points t o the first node. It can be
implemented as Singly in"ed ist and Doubly in"ed ist
CIRCULAR SIN(LY LIN'ED LIST
In a singly in"ed Circular ist is a list in which the last nodes of the list is pointed to the first
node of the list.
1;; );;; )1;;
CIRCULAR DOUBLY LIN'ED LIST
In a Circular Doubly in"ed ist (the first nodes previous field is connected to the last node and
last nodes ne0t field is connected to the first node.
);;; *;;; +;;;
Advanta?e
$he ist allow to traverse starting at any point
Fast access from first and last records
In both direction we allow the list to traverse
CURSOR I&PLE&ENTATION OF LIN'ED LIST
8any anguage such as :asic M Fortran do not support pointers. If in"ed ist are re9uired and
pointers are not available( then an alternative implementation must be used. $he method we will describe
is "nown as Cursor implementation. Cursor Implementation is very useful( where lin"ed list concept has
to be implemented without using pointers. In this case using array of Structures( but since the size of the
array of structure is fi0ed( this type of lists is referred as Static in"ed ist also referred as Cursor
implementation of in"ed ist.
!"# $ DATA STRUCTURES )1
1 );;;


); )1;; )1 1;;
+;;; ); *;;;
);;; *; +;;; *;;; +; );;;
UNIT I-LINEAR STRUCTURES
Inde0 values of array of structure are used in implementation of static (accessing is fast
compared to pointers in dynamic .!rray of Structures has to be initialized before storing the data( by
assigning the lin" value of each node between the inde0 of the immediate ne0t node. In the cursor list
array the node with the inde0; is used as the header. $he value; in the lin" field indicates the end of the
list. First node is always used for memory allocation it cannot be used for storage of data. Size of the
cursor list array will be always one less than the specified size.
S/ot <or=
Inde5
Data<or=
E/ement
Ne5t<or=
Lin;
#
-
- "
" !
! 8
8 B
B ,
, +
+ #
Initia/ised Cursor List
CURSOR ALLOCATION IN STATIC LIN'ED LIST
Steps to be followed to allocate a cursor in a Static .$o store data for the datafield( memory has
to be allocated which is always started from the first node of the cursor list. %et the free node /new
node2from the lin" of the first node of the cursorlist.!ssign the lin" of the new node to the lin" of the first
node. !ssign the lin" of the new node to zero.$he ne0t free node is found from the lin" of the first node of
the cursor list.
S/ot <or=
Inde5
Data<or=
E/ement
Ne5t<or=
Lin;
# - -
8
- - #
" # +
! - 8
8 -- ,
B ## "
, "" #
+ #- #
!"# $ DATA STRUCTURES )6
UNIT I-LINEAR STRUCTURES
CONTENTS OF T*E CURSOR LIST AFTER CREATIN( T)O LISTS
List
List -
Free /ist
* 5
CURSOR DEALLOCATION IN STATIC LIN'ED LIST
4emove a node from the list( memory has to be deallocated.!ssign the lin" of the removed
node with the lin" of the first node( which contains the inde0 of the ne0t free node. !ssign the lin" of the
first node with the inde0 of node to be removed.
DECLARATION FOR CURSOR I&PLE&ENTATION OF LL
$ypedef int Ptr$oNodeE
$ypedef Ptr$oNode istE
$ypedef Ptr$oNode PositionE
Goid intialisecursorspace/void2E
ist ma"eempty/ist 2E
Int Isempty /const ist 2E
Int Islast/const position P(const ist 2E
Position Find/3lemnt $ype F(ist 2E
Goid delete/3lement $ype F(sit 2E
Position Findprevious/3lementtype F(ist (Position P2E
Goid deletelist/ist 2E
Position Aeader/const ist 2E
Position First/const ist 2E
Position !dvance/const position P2E
!"# $ DATA STRUCTURES )7
)) ** ++ N>
);;

);) );* N>
N>
UNIT I-LINEAR STRUCTURES
SSPlace in the implementation file
Struct Node
H
3lement$ype 3lementE
Position Ne0tE
IE
Struct Node cursorspace<spacesize=E
ROUTINES CURSOR ALLOC AND CURSOR FREE
Static Position Cursor !lloc /void2
H
Position PE
PJCursorspace<;=.Ne0tE
Cursorspace<;=.Ne0tJCursorspace<P=.Ne0tE
return pE
I
Static Goid Cursorfree/position P2
H
Cursorspace<p=.Ne0tJCursorspace<;=.Ne0tE
Cursorspace<;=.Ne0tJpE
I
It shows the cursor implementation of malloc and free. If there is no space available( our routine
does the correct thing by PJ;(it indicates no more cells left.
S/ot E/ement Ne5t
# - B
: .
- 9 #
" *eader ,
! - #
8 *eader #
B - !
, c +
+ d -
. e #
# a
If the value of ist is 1 and the value of 8 is +( then represents the list a( b( e
and 8 represents the list c( d( f
!"# $ DATA STRUCTURES )?
UNIT I-LINEAR STRUCTURES
FUNCTION TO TEST )*ET*ER A LL IS E&PTY
int isempty /ist 2 <4eturn true if is empty=
H
return Cursorspace<=.Ne0tJJ;E
I
FUNCTION TO TEST )*ET*ER P IS LAST IN LL
FIND ROUTINE
Position Find/3lement $ype F(ist 2
H
Position PE
PJCursorSpace<l=.Ne0tE
Khile /P MM CursorSpace<P=.3lementLJF2
PJCursorspace<P=.Ne0tE
return PE <4eturn Position of F in E; if not found=
I
DELETE ROUTINE FOR LL
Goid delete /3lement $ype F(ist 2
H
Position P($mpcellE <Delete first occurrence of F from a ist=
PJFindPrevious/F(2E
if /LIslast /P(22
H
$mpcellJCursorSpace<P=.Ne0tE
CursorSpace<P=.Ne0tJCursorspace<$mpcell=.Ne0tE
CursorFree/$mpcell2E
I
I
INSERTION ROUTINE FOR LL
!"# $ DATA STRUCTURES
int islast/Position P(ist 2 <4eturn true if P is in last Position in ist =
H
return Cursorspace<P=.Ne0tJJ;E
I
)Q
UNIT I-LINEAR STRUCTURES
Pointer Im1/ementation Cursor Im1/ementation
Data are stored in a collection of structures.
3ach structure contains a data and ne0t
structures.
Data are stored in a global array of
structures.Aere array inde0 is considered as
address
8alloc function is used to create a node
and free function is used to release the cell. It maintains a list of free cells called
cursors space in which slot ; is considered
as a header and Ne0t is e9uivalent to the
pointer which points to the ne0t slot.
APPLICATION OF LIN'ED LIST
Polynomials
4adi0 Sort
8ultilist
!"# $ DATA STRUCTURES
Goid insert/3lement $ype F(ist (Position P2
H
Position $mpcellE$mpcellJcursoralloc/2E
If/$mpcellJJ;2
Fatal3rror/N&ut of SpaceT2E
Cursorspace<$mpcell=.3lementJFE
Cursorspace<$mpcell=.Ne0tJCursorspace<p=.Ne0tE
CursorSpace<P=.Ne0tJ$mpcellE
I
*;
UNIT I-LINEAR STRUCTURES
POLYNO&IAL ADT
In Polynomial !D$ each node consists of Coefficient and e0ponent of a term of the Polynomial.
TYPE DECLARATION FOR ARRAY I&PLE&ENTATION OF T*E POLYNO&IAL ADT
PROCEDURE TO INITIALICE A POLYNO&IAL TO CERO
PROCEDURE TO ADD T)O POLYNO&IAL
P 0#6
###
D86
8
D
P-0 "6
..#
--6
!.-
D6D8
LIN'ED LIST REPRESENTATION OF T)O POLYNO&IALS

P
P*
!"# $ DATA STRUCTURES
typedef Struct
H
int Coeff!rray <8a0Degree -)=E
int AighpowerE
ID polynomialE

Goid UeroPolynomial/Polynomial Poly2
H
int iE
for/iJ;EiVJ8a0degreeEi--2
PolyCoef!rray<i=J;E
PolyAighPowerJ;E
I
*)
1 )5

) ; ); );;;
.* )5Q*


)) ) + )QQ; 1 ;
UNIT I-LINEAR STRUCTURES
PROCEDURE TO ADD T)O POLYNO&IAL
E5am1/e
P"0"6
..#
--6
!.-
D#6
###
D86
!
D6DB

P+ Sum
PROCEDURE TO &ULTIPLY T)O POLYNO&IAL
Goid multPolynomial /Const Polynomial Poly)Const Polynomial Poly *(Polynomial PolyProd2
H
int i('E
zeroPolynomial/PolyProd2E
polyProdAighPowerJPoly)AighPower-Poly*ghPowerE
if/PolyProdAighPowerP8a0degree2
error/W30ceeded arraysizeO2E
else
for/iJ;EiVJPoly)AighPowerEi--2
for/'J;E'VJPoly*AighPowerE'--2
PolyProdcoefarray<i-'=-JPoly)coefarray<i=DPoly*coefarray<'=E
I
!"# $ DATA STRUCTURES
Goid !ddPolynomial/Const polynomial Poly)(Const Polynomial Poly*(Polynomial PolySum2
H
int iE
zeroPolynomial/PolySum2E
PolySumAighPowerJ8a0/Poly)..XAighPower(Poly*AighPower2E
For/iJPolysumAighPowerEi.J;Ei..2
PolySumCoefarray<i=JPoly)Coeffarray<i=-Poly*coeffarray<i=E
I
**
+ )QQ; * )5Q* ); );;; 1 )5 )) ) 6
UNIT I-LINEAR STRUCTURES
E6A&PLE
PR #6
###
D86
8
D
P-0"6
..#
--6
!.-
D6D8
Ste1 0 PolyProdAighPowerJPoly)AighPower-Poly*ighPowerE
7###D..#
7-..#
for/iJ;EiVJ);;;Ei--2
for/'J;E'VJ)QQ;E'--2
PolyProdcoefarray<;-;=J PolyProdcoefarray<;-;=-Poly)coefarray<;=DPoly*coefarray<;=E
J;-);D+
coefarray<;= J+;
<#6
###
D86
8
D= E <"6
..#
--6
!.-
D6D8=7@"#6
-..#
--#6
-!.-
D#6
##
D8#6
###
D86
-##!
-
#6
8#B
D886
8
D-86
!
D"6
..#
--6
!.-
D6D8A
$he 4unning $ime of the multiplication routine is proportional to the product of the degree of the two input
polynomial.
TYPE DECLARATION FOR LIN'ED LIST I&PLE&ENTATION OF POLYNO&IAL ADT
$ypedef Struct Node DPtr$oNodeE
Struct poly
H
int coefficient E
int e0ponentE
Ptr$oNode Ne0tE
Itypedef Ptr$oNode Polynomial
!"# $ DATA STRUCTURES *+
UNIT I-LINEAR STRUCTURES
RADI6 SORT
It is otherwise "nown as card sort.4adi0 Sort is in the form of :uc"et Sort.It can be performed
with N integer in the range ) to 8 /; to 8.)2
First Ste1 0!ll the elements are sorted accordingly to S:
Second Ste1 0!ll the numbers are arranged to the ne0t S: and the process is repeated (>ntil it reaches
8S: of numbers.
Example:84 14 32 960 1 0 128 400 55 60
$he input is ); numbers arranged randomly
Ste1 0Sorts by the S:
6;
5;;
;
Q6;
) +* )5
?5
11 )*?
; ) * + 5 1 6 7 ? Q
A9ter Pass -.B#F#F!##FB#F"-F+!F!F88F-+
Ste1 -
;
5;;
)5
)
)*? +* 11 6;
Q6;
?5
; ) * + 5 1 6 7 ? Q
A9ter Pass -- !##F#FF!F-+F"-F88F.B#FB#F+!
Ste1 "
?5
6;
11
+*
)5
)
;
)*? 5;; Q6;
; ) * + 5 1 6 7 ? Q
A9ter Pass " - #FF!F"-F88FB#F+!F-+F!##F.B#
!"# $ DATA STRUCTURES *5
UNIT I-LINEAR STRUCTURES
4unning $ime is /P/N-:22 where P is the number of passes (N is the number of elements to sort.:
is the number of :uc"ets.
&ULTI LISTS
8ore complicated application of lin"ed list is multilist. It is useful to maintain student registration(
3mployee involved in different pro'ects etc.( 8ultilist saves space but ta"es more time to implement.
&u/ti/ist Im1/ementation For Em1/o2ee ProGect A//ocation
!n employee can involve in any number of pro'ects and each pro'ect can be implemented by any
number of employees. 3mployee 3) is wor"ing on pro'ect P)( 3* is wor"ing on pro'ect P* M 3+ is wor"ing
on pro'ect P). Pro'ect P) is implemented by the 3mployees 3) M 3+. Pro'ect P* is implemented by the
3mployee 3*. E
T*E STAC' ADT
STAC' &ODEL
! stac" is a linear data structure which follows ast In First &ut /IF&2 principle( in which both
insertion and deletion occur at only one end of the list called the $op.
E5am1/e R . Pile of coins.( a stac" of trays in cafeteria.
&ODEL OF STAC'
POP<S= PUS*<6FS=
TOP<S=
!"# $ DATA STRUCTURES *1
Stac;<S=
3)
3* 3+
P)
P*
UNIT I-LINEAR STRUCTURES
TOP
Stac; &ode/
OPERATIONS ON STAC'
$he fundamental operations performed on a stac" are
). Push
*. Pop
PUS*
$he process of inserting a new element to the top of the stac". For every push operation the top is
incremented by ).

To1 -#
To1 To1 # #
Em1t2 Stac; A9ter insertin? A9ter insertin?
an e/ement # an e/ement -#
POP
$he process of deleting an element from the top of stac" is called pop operation. !fter every pop
operation the top pointer is decremented by ).
To1 +
, To1 ,
-8 -8 -8
Stac; Initia//2 A9ter t4e A9ter t4e
e/ement + is e/ement , is
de/eted de/eted
To1 -It 4eturns the value at the top node

E6CEPTIONAL CONDITIONS
!"# $ DATA STRUCTURES
C
A
B
*6
UNIT I-LINEAR STRUCTURES
OverF/o3
!ttempt to insert an element when the stac" is full is said to be overflow.
UnderF/o3
!ttempt to delete an element( when the stac" is empty is said to be >nderflow
I&PLE&ENTATION OF STAC'
Stac" can be implemented using arrays and in"ed ist.

+;;;
"### -### ###
LIN'ED LIST I&PLE&ENTATION OF STAC'
Y In Stac"(both the P>SA and P&P operation can be done at the front of the list.
Y $op e0amines the element at the front of the list( returning its value
TYPE DECLARATION FOR LIN'ED LIST I&PLE&ENTATION OF T*E STAC'
Struct NodeE
typedef Struct Node DPtr$oNodeE
typedef Ptr$oNode Stac"E
int Is3mpty /Stac" S2E
Stac" CreateStac" /void2E
void 8a"e3mpty /Stac" S2E
void push /3lement type F( Stac" S2E
3lement$ype $op /Stac" S2E
void pop /Stac" S2E
Struct Node
H
3lement type 3lement E
Ptr$oNode Ne0tE
IE
ROUTINE TO TEST )*ET*ER T*E STAC' IS E&PTY
!"# $ DATA STRUCTURES *7
); N> *; );;; +; *;;;
UNIT I-LINEAR STRUCTURES
int Is3mpty /Stac" S2
H
return SNe0t J J N>E
I
ROUTINE TO CREATE AN E&PTY STAC'
Stac" CreateStac" /void 2
H
Stac" SE
S J malloc /Sizeof /Struct Node22E
if /S J J N>2
Fatal3rror /Z &utof SpaceZ2E
8a"e3mpty /s2E
return SE
I
void 8a"e3mpty /Stac" S2
H
if /S J J N>2
3rror /Z Create Stac" FirstZ2E
else
while /L Is3mpty /s22
pop /s2E
I
Chec" the condition if S is N> /or2not(S is not N>(by using the P&P function in the stac"
P&P all the elements to ma"e the empty stac"
!"# $ DATA STRUCTURES *?
UNIT I-LINEAR STRUCTURES
ROUTINE TO PUS* AN ELE&ENT ONTO A STAC'
Goid push /3lement $ypeF( Stac" S2
H
Ptr$oNode $mpcellE
$empcell J malloc /sizeof /Struct Node22E
If /$empcell J J N>2
Fatal3rror /Z&ut of SpaceZ2E
else
H
$empcell3lement J FE
$empcellNe0t J SNe0tE
SNe0t J $empcellE
I
I
It is implemented as an insertion into the front of the lin"ed list(where the front of the list serves as
top of the stac".
E5am1/e 0"#F-#F#
> 67"#

S
Now the Stac" of S is N>(insert the above element by using P>SA operation
E/ement Ne5t

Tm1Ce// S Sne5t
Assi?n S-->Hne5t to Tm1ce//ne5t
!"# $ DATA STRUCTURES
N>
*Q
NULL );
UNIT I-LINEAR STRUCTURES
Sne5t
ii=67-#
E/ement Ne5t ###
Tm1ce// Sne5t
Assi?n S-->Hne5t to Tm1ce//ne5t
E/ement Ne5t ###
Sne5t
iii=67"#
E/ement Ne5t -### ###

"###
Tm1ce// Sne5t
Assi?n Sne5t to Tm1ce//ne5t
E/ement Ne5t -### ###

+;;;
Sne5t
ROUTINE TO RETURN TOP ELE&ENT IN A STAC'
3lementtype $op /Stac" S2
H
If /L Is3mpty /s22
return SNe0t3lementE
3rror /Z3mpty Stac"Z2E
return ;E
I
!"# $ DATA STRUCTURES +;
);
); N> *;
); N> *;
); N> *; );;; +;
); N> *; );;; +;
UNIT I-LINEAR STRUCTURES


Sne5t
To1
$op is performed by e0amining the element in the first position of the list.Chec" whether the
stac" is empty or not (if it is not empty return Sne0telement as the top element. $he first position of
the list is the top element in the stac"
Sne5te/ement7"#
ROUTINE TO POP FRO& A STAC'
void pop /Stac" S2
H
Struct Node D$empcellE
If /Is3mpty /S22
3rror /Z3mpty Stac"Z2E
else
H
$empcell J SNe0tE
SNe0t J SNe0tNe0tE
Free /$empcell2E
I
I
Pop operation is to delete from the front of the list
POP -### ###

"###
Sne5t
Tem1ce//
!ssign Sne0t as $empcell and assign Sne0tne0t as Sne0t and pop the element which is
present in the $empcell
POP -### ###

Sne5t
Tem1ce//
!"# $ DATA STRUCTURES +)
); N> *; );;; +;
); N> *; );;; +;
); N> *; );;;
UNIT I-LINEAR STRUCTURES
###
SNe5t
ARRAY I&PLE&ENTATION OF STAC'
In this implementation each stac" is associated with a pop pointer( which is .) for an empty stac".
Y $o push an element F onto the stac"( $op Pointer is incremented and then set Stac" <$op= J F.
Y $o pop an element( the stac" <$op= value is returned and the top pointer is decremented.
Y Pop on an empty stac" or push on a full stac" will e0ceed the array bounds.
STAC' DECLARATION $ARRAY I&PLE&ENTATION
Stac" is defined as a pointer to a structure. $he structure contains the $opofStac" and capacity
fields. &nce the ma0imum size is "nown(the stac" array can be dynamically allocated.
Struct Stac"4ecordE
typedef Struct Stac"4ecord DStac"E
int Is3mpty /Stac" S2E
intIsfull/Stac" S2E
Stac" CreateStac" /int 8a0elements2E
void 8a"e3mpty /Stac" S2E
void DisposeStac"/Stac" S2E
void push /3lement type F( Stac" S2E
3lement$ype $op /Stac" S2E
void pop /Stac" S2E
3lement $ype topandPop/Stac" S2E
Stac; im1/ementation is a d2namica//2 a//ocated
Bdefine empty$&S/.)2
Bdefine 8inistac"Size/12
Struct Stac"4ecord
H
int capacityE
!"# $ DATA STRUCTURES +*
); N>
UNIT I-LINEAR STRUCTURES
int $opofStac"E
3lement $ype D!rrayE
IE
STAC' CREATION-ARRAY I&PLE&ENTATION
Stac" CreateStac"/int 8a0elements2
H
Stac" SE
If/8a03lements V 8inStac"Size2
3rror/NStac" Size is too smallO2E
SJmalloc/Sizeof/Struct Stac"4ecord22E
If/SJJN>2
Fatal3rror/N&ut of SpaceO2E
SarrayJmalloc/Sizeof/3lement type2D8a03lements2E
If/SarrayJJN>2
Fatal3rror/N&ut of SpaceO2E
SCapacityJ8a03lementsE
8a"e3mpty/S2E
return SE
I
ROUTINE FOR FREEIN( STAC'-ARRAY I&PLE&ENTATION
Goid DisposeStac"/Stac" S2
H
if/SLJN>2
H
free/Sarray2E
free/S2E
I
I
!"# $ DATA STRUCTURES ++
UNIT I-LINEAR STRUCTURES
Dispose stac" should be written to free the Stac" structure.It first frees the stac" array and then
stac" structure.
ROUTINE TO TEST )*ET*ER A STAC' IS E&PTY
Int Is3mpty/Stac" S2
H
return S.P$opofStac"JJ3mpty$&SE
I
3mpty Stac"
ROUTINE TO PUS* AN ELE&ENT ONTO A STAC'
void push /3lement $ype 0( Stac" S2
H
if /IsFull /S22
3rror /ZFull Stac"Z2E
else
Sarray<--S$opofStac"=J0EI
F F F
$&S +;
$&S *; *;
$op of Stac" ); ); );
ROUTINE TO RETURN TOPOFSTAC'
3lement$ype $op/Stac" S2
H
if/L Is3mpty /S22
return Sarray<S$opofStac"=E
3rror/N3mpty Stac"O2E
4eturn ;E
I
!"# $ DATA STRUCTURES +5
UNIT I-LINEAR STRUCTURES
It return the $op3lement of the Stac"
To1 o9 Stac;7"#
ROUTINE TO POP AN ELE&ENT FRO& T*E STAC'
void pop /Stac" S2
H
if /Is3mpty /S22
3rror /Z3mpty Stac"Z2E
else
H
S$opofStac"..E
I
Pop
+; $opofStac"
*;
);
$op of Stac" can be decremented by )while popping the element
*; $&S
# # TOS Em1t2 Stac;

APPLICATIONS OF STAC'
Some of the applications of stac" are R
<i= In9i5 to Post9i5
<ii= Ba/ancin? t4e s2m:o/s
<iii= To3ers o9 *annoi
<iv= Function Ca//s>
<v= Reversin? a Strin?>
<vi= Eva/uatin? arit4metic e51ression
!"# $ DATA STRUCTURES +1
UNIT I-LINEAR STRUCTURES
INFI6
In Infi0 notation( $he arithmetic operator appears between the two operands to which it is being applied.
For e0ample R . ! S : - C
POSTFI6
$he arithmetic operator appears directly after the two operands to which it applies. !lso called reverse
polish notation. //!S:2 - C2
For e0ample R . !: S C -
PREFI6
$he arithmetic operator is placed before the two operands to which it applies. !lso called as polish
notation. //!S:2 - C2
For e0ample R . -S!:C
INFI6 PREFI6 <or= POLIS* POSTFI6 <or= RE%ERSE POLIS*
). /! - :2 S /C . D2 S-!: . CD !: - CD . S
*. ! - :D/C . D2 -!D: . CD !:CD . D -
+. F D ! S : . D . S D F!:D F !D:SD.
5. F - [ D /! . :2 S -FSD[ . !: . CD F[!: . DCD . S - /C . D2
1. ! D:SC - D - S D !:CD !: D C S D -
INFI6 TO POSTFI6 CON%ERSION
Ke can use a Stac" to convert an e0pression infi0 to postfi0.
4ead the infi0 e0pression one character at a time until it encounters the delimiter. ZBZ
Step ) R If the character is an operand( place it on to the output.
Step * R If the character is an operator( push it onto the stac". If the stac" operator has a higher
or e9ual priority than input operator then pop that operator from the stac" and place it onto
the output.
Step + R If the character is a left paraenthesis( push it onto the stac".
Step 5 R If the character is a right paraenthesis( pop all the operators from the stac" till it
!"# $ DATA STRUCTURES +6
UNIT I-LINEAR STRUCTURES
encounters left parenthesis( discard both the parenthesis in the output.
E5am1/e0 aD:EcD<dEeD9=E?I
Step )R 4ead the 3lements from the leftend to right end.
Step *R 4ead the symbol WaT and it is passed through to the oSp.$hen read W-T( it is operator
so(Pushed onto the stac".
Step +R Ne0t WbT is read and passed through to the oSp.
Step 5RNe0t WDT is read( the entry of the operator stac" is higher precedence when compared to the
top entry operator in stac".So push it into the stac".
Step 1RNe0t WcT is read and push it into oSp.
Step 6RNe0t W-T is read( the top entry operator WDT in the stac" is higher precendence when
compared to the entry of the operator W-T. So pop the highest precedence WDT and place it in
the oSp.
Step 7R $hen other W-T is push into the stac" which is e9ual priority but not lower.
Step ?RNe0t symbol( W/W is read which is being highest precedence( plaed on the stac".
Step QR4ead WdT and place it in oSp.
Step );R 4ead the operator WDT( open paranthesis donot get removed e0cept when a closed paranthesis
is being processed.
Step ))RTeT is read and push it to oSp.
Step )*R4ead a symbol W-T( compare the precedence and pop WDT into oSp and pushT-T into the stac".
Step )+R 4ead WfT and placed in oSp.
Step )5R4ead W2T stac" is emptied bac" upto W/W.
Step )1R 4ead WDT and push it into the stac".
Step )6RTgT is read and placed in oSp.
Step )7R Now the iSp is empty(so pop all the symbols from the stac" until it is empty and placed it in
oSp symbols.
In9i5 to Post9i5 E51ression 0aD:EcD<dEeD9=E? - a :cEDd eE9DED
!"# $ DATA STRUCTURES +7
-
-
a
a b

a
-
D a b
-
D a bc
-
a bcD-
-
/
a bcD-
-
/
a bcD-d
UNIT I-LINEAR STRUCTURES
C4aracter Stac; Out1ut

a
-
b
D
c
-
/
d
!"# $ DATA STRUCTURES +?
a bcD-d
a bcD-deDf-
a bcD- deDf-
a bcD- deDf-
a bcD-d eDf-D-
-
/
D
-
/
D
a bcD-de
-
/
- a bcD-deD
-
/
- a bcD-deDf
-
-
D
-
D

UNIT I-LINEAR STRUCTURES
D
e
-
f
2
D
g
!"# $ DATA STRUCTURES +Q
/
/
/
/

/
<
/


UNIT I-LINEAR STRUCTURES
BALANCIN( T*E SY&BOLS
Compilers chec" the programs for errors( a lac" of one symbol will cause an error.
! Program thet chec"s whether everything is balanced.
3very right paranthesis should have its left paranthesis.
Chec" for balancing the paranthesis brac"ets braces and ignore any other character

4ead one character at a time until it encounters the delimiter \B].
Ste1 0 - If the character is an opening symbol( push it onto the stac".
Ste1 - 0 - If the character is a closing symbol( and if the stac" is empty report an error as
missing opening symbol.
Ste1 " 0 - If it is a closing symbol and if it has corresponding opening symbol in the stac"( P&P
it from the stac". &therwise( report an error as mismatched symbols.
Ste1 ! 0 - !t the end of file( if the stac" is not empty( report an error as 8issing closing symbol.
&therwise( report as :alanced symbols.
et us consider the e0pression as //:D:2.H5D!DCIS<*D!=2 B
<<BEB=-J!EAECKL@-EAA= I
Read C4aracter Stac;
/
/
2
!"# $ DATA STRUCTURES 5;
/
H
/

/
<
/


UNIT I-LINEAR STRUCTURES
H
I
<
=
2
T4us a// t4e 1arant4esis are :a/anced
RE%ERSIN( A STRIN(>
8ain characteristics of stac" is reversing the order of contents
Pushing each character until end of the string
Individual character are popped off from the stac".
$he last character pushed into the stac" would be the first character to be popped off from the
stac".
E5am1/e 0T4e Strin? Com1uter is reversed :2 usin? t4e Stac; o1eration as retu1moc
!"# $ DATA STRUCTURES 5)
UNIT I-LINEAR STRUCTURES

Po1 t4e Strin? one :2 one unti/ t4e stac; is em1t2
!"# $ DATA STRUCTURES
c
o
u
p
m
e
t
r
c
c
o
c
o
m
c
o
p
m
c
o
u
m
p
c
o
u
p
m
t
c
o
u
p
m
e
t
5*
UNIT I-LINEAR STRUCTURES
E%ALUATIN( POSTFI6 E6PRESSION
4ead the postfi0 e0pression one character at a time until it encounters the delimiter \B].
Step ) R . If the character is an operand( push its associated value onto the stac".
Step * R . If the character is an operator( P&P two values from the stac"( apply the operator to
them and push the result onto the stac".
E5am1/e 0 et us consider the symbols !( :( C( D( 3 had the associated values R !:DCD3S.-
Symbol Galue
! 5
: 1
C 1
D ?
3 *
Read C4aracter Stac;
! 5
1
: 5
D *;

C 1
*;
?
1
D *;
!"# $ DATA STRUCTURES 5+
UNIT I-LINEAR STRUCTURES
*
?
3 1
*;
5
1
S *;
)
. *;
- *)
Eva/uation o9 Post9i5 E51ression o9 ABECDEL-D Su:stitue t4e va/ues ?iven a:ove and t4e Resu/t is
->
TO)ERS OF *ANOI
$owers of Aanoi can be easily implemented using recursion.&b'ective of the problem is moving a
collection of N dis"s of decreasing size from one pillar to another pillar. $he movement of the dis" is
restricted by the following rules.
4ule ) R &nly one dis" could be moved at a time.
4ule * R No larger dis" could ever reside on a pillar on top of a smaller dis".
4ule + R ! +rd pillar could be used as an intermediate to store one or more dis"s( while they
were being moved from source to destination.
$ower ) $ower * $ower +
! : C
Initia/ Setu1 o9 To3er o9 *anoi
!"# $ DATA STRUCTURES 55
UNIT I-LINEAR STRUCTURES
RECURSI%E SOLUTION
N - re1resents t4e num:er o9 dis;s>
Step ). If N J )( move the dis" from ! to C.
Step *. If N J *( move the )
st
dis" from ! to :. $hen move the *
nd
dis" from ! to C( $he move the )
st

dis" from : to C.
Step +. If N J +( 4epeat the step /*2 to more the first * dis"s from ! to : using C as intermediate.$hen the
+
rd
dis" is moved from ! to C. $hen repeat the step /*2 to move * dis"s from : to C using ! as
intermediate.
In general( to move N dis"s. !pply the recursive techni9ue to move N . ) dis"s from ! to : using
C as an intermediate. $hen move the N
th
dis" from ! to C. $hen again apply the recursive techni9ue to
move N . ) dis"s from : to C using ! as an intermediate.
RECURSI%E ROUTINE FOR TO)ERS OF *ANOI
void hanoi /int n( char s( char d( char i2
H
SD n no. of dis"s( s source( d destination i intermediate DS
if /n J J )2
H
print /s( d2E
returnE
I
else
H
hanoi /n . )( s( i( d2E
print /s( d2
hanoi /n.)( i( d( s2E
returnE
I
I
!"# $ DATA STRUCTURES 51
UNIT I-LINEAR STRUCTURES
Source Pi//ar Intermediate Pi//ar Destination Pi//ar
$ower ) $ower * $ower +
). 8ove $ower) to $ower+
*. 8ove $ower) to $ower*
$ower ) $ower * $ower +
+. 8ove $ower + to $ower *
$ower ) $ower * $ower +
5. 8ove $ower ) to $ower +
$ower ) $ower * $ower +
1. 8ove $ower * to $ower )
$ower ) $ower * $ower +
6. 8ove $ower * to $ower +
!"# $ DATA STRUCTURES 56
UNIT I-LINEAR STRUCTURES
$ower ) $ower * $ower +
7.8ove $ower ) to $ower +
$ower ) $ower * $ower +
Since dis;s are moved 9rom eac4 to3er in a LIFO mannerFeac4 to3er ma2 :e considered as a
Stac;>Least Num:er o9 moves reMuired to so/ve t4 e1ro:/em accordin? to our a/9orit4m is ?iven :2F
O<N=7O<N-=DDO<N-=
7-
N
-
FUNCTION CALLS
Khen a call is made to a new function all the variables local to the calling routine need to be
saved( otherwise the new function will overwrite the calling routine variables. Similarly the current
location address in the routine must be saved so that the new function "nows where to go after it is
completed.
RECURSI%E FUNCTION TO FIND FACTORIAL
Int fact/int n2
H
int SE
if/nJJ)2
return/)2E
!"# $ DATA STRUCTURES 57
8ain/2

Call
balance/2
:alance/2
Call push/2
4eturn
Push/2
4eturn
UNIT I-LINEAR STRUCTURES
else
SJnDfact/n.)2E
return/S2
I
T*E NUEUE ADT
NUEUE &ODEL
! #ueue is a linear data structure which follows First In First &ut /FIF&2 principle( in which
insertion is performed at one end and deletion is performed at another end.
3nd at which insertion are made is referred as Rear End. 3nd at which deletion are made is
referred as Front End>First element placed in a 9ueue will be at the end of the 9ueue. ast element placed
in a 9ueue will be at the start of the 9ueue.#ueue is termed as First In First &ut<FIF&= lists
DeMueue<N= EnMueue<N=
Front Rear
E5am1/e 0 )aitin? Line in Reservation CounterF
OPERATIONS ON NUEUE
$he fundamental operations performed on 9ueue are
). 3n9ueue
*. De9ueue
EnMueue 0 $he process of inserting an element in the 9ueue.
DeMueue 0 $he process of deleting an element from the 9ueue.
E6CEPTION CONDITIONS
Over9/o3 0 !ttempt to insert an element( when the 9ueue is full is said to be overflow condition.
Under9/o3 0 !ttempt to delete an element from the 9ueue( when the 9ueue is empty is said to be
underflow.
I&PLE&ENTATION OF NUEUE
!"# $ DATA STRUCTURES 5?

#ueue
UNIT I-LINEAR STRUCTURES
#ueue can be implemented using arrays and pointers.
ARRAY I&PLE&ENTATION
# is associated with two pointers namely rear pointer and front pointer. $o insert an element F
onto the #ueue #( the rear pointer is incremented by ) and then set
Nueue @RearA 7 6
$o delete an element( the #ueue <Front= is returned and the Front Pointer is incremented by ).
.)
4 ; ) * + 5
F E&PTY NUEUE
ROUTINE TO INSERT AN ELE&ENT IN A NUEUE
void 3n9ueue /int F2
H
if /rear P J ma0 C !rraysize2
print /Z #ueue overflowZ2E
else
H
4ear J 4ear - )E
#ueue <4ear= J FE
I
I
E6A&PLE
);
; ) * + 5
RFF
EnMueue 8

); )1
; ) * + 5
F R
EnMueue -#
); )1 *;
; ) * + 5
!"# $ DATA STRUCTURES 5Q
UNIT I-LINEAR STRUCTURES
F R
ROUTINE FOR DENUEUE
void delete / 2
H
if /Front V ;2
print /Z #ueue >nderflowZ2E
else
H
F J #ueue <Front=E
if /Front J J 4ear2
H
Front J ;E
4ear J .)E
I
else
Front J Front - ) E
I I
E6A&PLE
); )1 *;
; ) * + 5
F R
!ssign #ueue<front=as F(#ueue<front=J);(delete the corresponding element as FIF& manner
)1 *;
; ) * + 5
F R
*;
; ) * + 5
F R
.) ; ) * + 5
R F
In De9ueue operation( if Front J 4ear( then reset both the pointers to their initial values.
/i.e. F J ;( 4 J .)2
!"# $ DATA STRUCTURES 1;
UNIT I-LINEAR STRUCTURES
I&PLE&ENTATION OF NUEUE USIN( LIN'ED LIST
3n9ueue operation is performed at the end of the list and De9ueue operation is performed at the
front of the list.
NUEUE ADT

F
!"# $ DATA STRUCTURES
); *; N>
1)
UNIT I-LINEAR STRUCTURES
DECLARATION FOR LIN'ED LIST I&PLE&ENTATION OF NUEUE ADT

ROUTINE TO C*EC' )*ET*ER T*E NUEUE IS E&PTY
ROUTINE TO C*EC' AN E&PTY NUEUE
Struct Create#ueue / 2
H
#ueue #E
# J 8alloc /Sizeof /Struct Node22E
if /# J J N>2
3rror /Z&ut of SpaceZ2E
!"# $ DATA STRUCTURES 1*
Struct NodeE
typedef Struct Node D #ueueE
int Is3mpty /#ueue #2E
#ueue Create#ueue /void2E
void 8a"e3mpty /#ueue #2E
void 3n9ueue /int F( #ueue #2E
void De9ueue /#ueue #2E
Struct Node
H
int 3lementE
Struct Node DNe0tE
ID Front J N>( D4ear J N>E
int Is3mpty /#ueue #2 SS returns boolean value S
H SS if # is empty
if /# Ne0t J J N>2 SS else returns ;
return /)2E
I
UNIT I-LINEAR STRUCTURES
8a"e3mpty /#2E
return #E
I
void 8a"e3mpty /#ueue #2
H
if /# J J N>2
3rror /ZCreate #ueue FirstZ2E
else
while /L Is3mpty /#2
De9ueue /#2E
i2


DeMueue
ii2
iii2
Em1t2Nueue
ROUTINE TO ENNUEUE AN ELE&ENT IN NUEUE
void 3n9ueue /int F2
H
Struct node DnewnodeE
newnode J 8alloc /sizeof /Struct node22E
if /4ear J J N>2
H
newnode data J FE
newnodeNe0t J N>E
Front J newnodeE
4ear J newnodeE
!"# $ DATA STRUCTURES 1+
*; N> );
*; N>
UNIT I-LINEAR STRUCTURES
I
else
H
newnode data J FE
newnode Ne0t J N>E
4ear ne0t J newnodeE
4ear J newnodeE
I I
E5am1/e0#F-#F"#
Data Ne5t
i2
Ne3node
Front Rear
ii2
Front Rear Ne3node
!ssign Newnode as rear
iii2
Front Rear Ne3node
!ssign Newnode as rear
!"# $ DATA STRUCTURES
); );;; *; N>
); );;; *; +;;; +; N>
15
); N>
UNIT I-LINEAR STRUCTURES
ROUTINE TO DENUEUE AN ELE&ENT FRO& T*E NUEUE
void De9ueue / 2
H
Struct node DtempE
if /Front J J N>2
3rror/Z#ueue is underflowZ2E
else
H
temp J FrontE
if /Front J J 4ear2
H
Front J N>E
4ear J N>E
I
else
Front J Front Ne0tE
Print /tempdata2E
free /temp2E
I
I
Front Rear
Assi?n t4e 9ront e/ement as tem1 and 9rontne5t as 9ront to de/ete t4e tem1 data>

Front Rear
!"# $ DATA STRUCTURES
); );;; *; +;;; +; N>
*; +;;; +; N>
11
UNIT I-LINEAR STRUCTURES
Assi?n t4e 9ront e/ement as tem1 and 9rontne5t as 9ront to de/ete t4e tem1 data>


Front
Rear
I9 9ront and rear are eMua/ assi?n to nu// and de/ete t4e corres1ondin? 9ront e/ement
Front7rear7NULL
CIRCULAR NUEUE
In Circular #ueue( the insertion of a new element is performed at the very first location of the
9ueue if the last location of the 9ueue is full( in which the first element comes 'ust after the last element.
AD%ANTA(ES
It overcomes the problem of unutilized space in linear 9ueues( when it is implemented as arrays.
PICTORIAL REPRESENTATION OF CIRCULAR NUEUE
N@8A
N@#A
N@!A
N@"A N@A
N@-A
N@8A Front
N@#A
N@!A
N@"A N@A
Rear N@-A
!"# $ DATA STRUCTURES 16
+; N>


#
!#
-#
"#
UNIT I-LINEAR STRUCTURES
INSERTION IN A CIRCULAR NUEUE
$o perform the insertion of an element to the 9ueue( the position of the element is calculated by the
relation as
Rear 7 <Rear D = O &a5siPe>
and then
Nueue @RearA 7 va/ue>
ROUTINE TO INSERT AN ELE&ENT IN CIRCULAR NUEUE
void C3n9ueue /int F2
H
if /Front J J /rear - )2 ^ 8a0size2
print /Z#ueue is overflowZ2E
else
H
if /front J J .)2
front J rear J ;E
else
rear J /rear - )2^ 8a0sizeE
C#ueue <rear= J FE
I
I
R F
E5am1/e #F-#F"# N@8A
N@#A
N@!A
N@"A N@A
N@-A
!"# $ DATA STRUCTURES 17
UNIT I-LINEAR STRUCTURES
Insert an e/ement # in a Circu/ar Nueue
rear J /rear - )2^ 8a0size
J/.)-)2^6J;
C9ueue<;= J# R F
N@8A
N@#A
N@!A

N@"A N@A
N@-A
ii=67-#
Insert an element *; in a Circular #ueue
rear J /rear - )2^ 8a0size
J/;-)2^6J)
CMueue@A 7-#
N@8A Front
N@#A
N@!A
Rear
N@"A N@A

N@-A
!"# $ DATA STRUCTURES 1?

#

#

-#
UNIT I-LINEAR STRUCTURES
iii=67"#
Insert an element +; in a Circular #ueue
rear J /rear - )2^ 8a0size
J/)-)2^6J*
CMueue@-A 7"#
N@8A Front
N@#A
N@!A
N@"A N@A
Rear
N@-A
$o perform the deletion( the position of the Front printer is calculated by the relation
%a/ue 7 CNueue @FrontA
Front 7 <Front D = O ma5siPe>
ROUTINE TO DELETE AN ELE&ENT FRO& CIRCULAR NUEUE
int CDe9ueue / 2
H
if /front J J .)2
print /Z#ueue is underflowZ2E
else
H
F J C#ueue <Front=E
if /Front J J 4ear2
Front J 4ear J .)E
else
Front J /Front - )2^ ma0sizeE
I
return /F2E I
!"# $ DATA STRUCTURES 1Q

#
-#

"#
UNIT I-LINEAR STRUCTURES
N@8A Front
N@#A

N@!A
N@"A N@A
R Rear
N@-A
!ssign FJC9ueue<front=
FJC9ueue<;=
FJ);
Front7<FrontD=Oma5siPe
J/;-)2^6
Front 7 N@8A
N@#A
N@!A
Front
N@"A N@A

N@-A Rear
!ssign FJC9ueue<front=
FJC9ueue<)=
FJ*;
FrontJ/Front-)2^ma0size
J/)-)2^6
Front 7-
!"# $ DATA STRUCTURES 6;

);
*;

+;


-#

"#
UNIT I-LINEAR STRUCTURES
N@8A
N@#A
N@!A
N@"A N@A


Rear Front
N@-A
DOUBLE ENDED NUEUE <DENUE=
In Double 3nded #ueue is another form of #ueue in which insertion and deletion are made at both the
front and rear ends of the #ueues.
inear De9ue
Circular De9ue
Front End>
Insertion Insertion Insertion
De/etion De/etion
Rear end
LINEAR DENUE
Insertion and Deletion are made at both the front and rear ends of the de9ue.If the frontend is in
the first position (you cannot insert the data at the front end.If rear end is in the last position cannot insert
the data at rear end.
CIRCULAR DENUE
Insertion and deletion are made at both front end and rear ends of the de9ue.Kith the position of
the Front and rear end(you can insert and delete data
!"# $ DATA STRUCTURES 6)



+;
B
8
.

!
" -
UNIT I-LINEAR STRUCTURES
Rear
Front
CIRCULAR DENUE REPRESENTATION AFTER DELETION AT REAR END
Rear End
Front End
CIRCULAR DENUE REPRESENTATION AFTER INSERTION AT FRONT END
Rear End

Front End
!"# $ DATA STRUCTURES
,
8
+

!
" -
B
8


!
" -
6*
B #
8
.

!
" -
B #
8

!
" -
UNIT I-LINEAR STRUCTURES
CIRCULAR DENUE REPRESENTATION AFTER INSERTION AT REAR END
Rear End

Front End
CIRCULAR DENUE REPRESENTATION AFTER DELETION AT FRONT END
Rear End

Front End
In1ut Restricted DeMue.It allows insertions at only one end of the list but allows deletion at both ends of
the list. Front Rear

De/etion
De/etion
Insertion
!"# $ DATA STRUCTURES 6+
UNIT I-LINEAR STRUCTURES
Out1ut Restricted DeMue-It allows deletion at only one end of the list but aloows insertion at both ends
of the list.
Front Rear

Insertion
De/etion Insertion
Advanta?e
It &vercomes the problem of >nutilised Space in inear #ueues(when it is implemented as array
PRIORITY NUEUES
Priority #ueue is a #ueue in which inserting an item or removing an item can be performed from
any position based on some priority.
APPLICATIONS OF NUEUE
D :atch processing in an operating system
D $o implement Priority #ueues.
D Priority #ueues can be used to sort the elements using Aeap Sort.
D Simulation.
D 8athematics user #ueueing theory.
D Computer networ"s where the server ta"es the 'obs of the client as per the 9ueue strategy.
!"# $ DATA STRUCTURES 65
UNIT I-LINEAR STRUCTURES
!"# $ DATA STRUCTURES 61
UNIT I-LINEAR STRUCTURES
UNIT I
T)O &AR'S NUETSION ANS)ER
>De9ine ADT <A:stract Data T21e=Q
!n !D$ is a mathematical model with a collection of operations defined on that model. &b'ects
such as lists( sets and graphs along with their operations can be viewed as abstract data type. Set !D$(
we have such operations as union( intersection( size and complement. Implementation of these
operations is written once in a program( any other part of the program that needs to perform an
operation on the !D$ by calling the appropriate function
IS$ !D$
S$!C@ !D$
#>3>3 !D$
->De9ine data structure>
Data structure is defined as a system of organizing related piece of information. It is the
specialized format for organizing and storing data. Data Structures are the methods of representing a
logical relationships between the individual data element related to the solution of the given problem.
">De9ine Linear and Non Linear data structure
inear data structures are data structures having a linear relationship between its ad'acent
elements. $he linear lists and linear array allowed one to insert and delete elements at any place in the list
at the beginning( at the end or in the middle. 3g. in"ed ist( !rrays( Stac"s( #ueue.
Non inear data structures are data structures donTt have a linear relationship between its ad'acent
elements( but had the hierarchical relationship. 30. %raph($ree.
!>)4at are di99erent t21es o9 Lin;ed ListQ
). Single lin"ed list
*. Double lin"ed list
+. Circular lin"ed list
8>)4at are di99erent t21es o9 Circu/ar Lin;ed ListQ
Circular Single lin"ed list
Circular double lin"ed list
B>List t4e :asic o1erations carried out in a /in;ed /istQ
Creation of list
Insertion of list
Deletion of list
8odification of list
$raversal of ist
,>De9ine a stac;
Stac" is an ordered collection of elements in which insertions and deletions are restricted to one
end. $he end from which elements are added and Sor removed is referred to as top of the stac". Stac"s are
also referred as NpilesO and Npush.down listsO.
!"# $ DATA STRUCTURES 66
UNIT I-LINEAR STRUCTURES
!"# $ DATA STRUCTURES 67
UNIT I-LINEAR STRUCTURES
+>De9ine a Mueue
#ueue is an ordered collection of elements in which insertions and deletions are restricted to one
end. $he end from which elements are added and S or removed is referred to as the rear end and the end
from which deletions are made is referred to as front end.
.>Di99erence :et3een Arra2s and Lin;ed List
Arra2s Lin;ed List
Size of any array is fi0ed Size of list is variable
It is necessary to specify the number of
elements during declaration
It is not necessary to specify the
number of elements during declaration
Insertion and deletions are difficult and
costly
Insertions and deletions are done in
less time
It occupies less memory than a lin"ed list It occupies more memory
Coding is easy Careful Coding is needed to avoid memory
errors.
#>)4at is sin?/e /in;ed /istQ
It is a linear data structure which consists a pointer field that points to the address of its ne0t
node/successor2 and the data item.
>De9ine *EAD 1ointer and NULL 1ointer
A3!D It contains the address of the first node in that list.
N> It indicates the end of the list structure.
->)4at is meant :2 dumm2 4eaderQ
It is a head node in the lin"ed list before the actual data nodes.
">De9ine dou:/e /in;ed /ist
It is linear data structure which consists of two lin"s or pointer fields
Ne0t pointer points to the address of the ne0t/successor2 node.
Previous pointer points to the address of the previous/predecessor2 node.
*eader
Ne5t
Previous
Pointer
!"# $ DATA STRUCTURES
BLIN' DATA POINTER FLIN'
6?
!) !5 !+ !* Aeader

); )); );; *; )*; )); +; null
UNIT I-LINEAR STRUCTURES
!>De9ine Circu/ar /in;ed /ist 3it4 t4e di99erent t21es o9 Circu/ar List
It is a list structure in which last node points to the first node there is no null value.
Circu/ar Sin?/2 Lin;ed List
In a singly in"ed Circular ist is a list in which the last nodes of the list is pointed to the first
node of the list.
1;; );;; )1;;
Circu/ar Dou:/2 Lin;ed List
In a Circular Doubly in"ed ist (the first nodes previous field is connected to the last node and
last nodes ne0t field is connected to the first node.
);;; *;;;
8>)rite o1erations t4at can :e done on stac;Q
P>SA
P&P
B>&ention a11/ications o9 stac;Q
a. 30pression Parsing
b. 3valuation of Postfi0
c. :alancing parenthesis
d. $ower of Aanoi
e. 4eversing a string

,>De9ine In9i5F 1re9i5 and 1ost9i5 notationsQ
Infi0 operators are placed in between the operands
Prefi0 operators are placed before the operands
Postfi0 &perators are placed after the operands.
+>)4at are t4e conditions t4at 9o//o3ed in t4e arra2 im1/ementation o9 MueueQ
43!4VF4&N$ 38P$[ #>3>3
F4&N$JJ43!4 &N3 3N$4[ #>3>3
43!4JJ!44![ SIU3 F> #>3>3
.>)4at are t4e conditions t4at cou/d :e 9o//o3ed in a /in;ed /ist im1/ementations o9
MueueQ
43!4JJA3!D 38P$[ #>3>3
43!4JJIN@/A3!D2&N3 3N$4[ #>3>3
N& F433 SP!C3 $& INS34$ F> #>3>3
!"# $ DATA STRUCTURES 6Q
1 );;;


); )1;; )1 1;;
+;;; ); *;;; );;; *; +;;; *;;; +; );;;
UNIT I-LINEAR STRUCTURES
-#>)4at are t4e conditions t4at cou/d :e 9o//o3ed in a /in;ed /ist im1/ementations o9
MueueQ
/43!4 8&D !44![ SIU3 -)2JJF4&N$ 38P$[ #>3>3
/43!4 8&D !44![ SIU3 -*2JJF4&N$F> #>3>3
F4&N$JJ43!4 &N3 3N$4[ #>3>3
->De9ine Circu/ar MueueQ
! circular 9ueue allows the 9ueue to wrap around upon reaching the end of the array.
Insertion and deletion are made at both front end and rear ends of the de9ue.
-->De9ine arra2 and /ist
!rray _ !rray is a non.primitive data structure. It can be defined as an ordered set( which
consists of fi0ed number of ob'ects. $here is no deletion or insertion operation on an array.
ist _ ist is defined as an ordered set of which consists of variable number of elements.
-">)4at are a// t4e a11/ications o9 Lin;ed ListQ
$ree traversal
Creation of a polynomial
Sorting
Creation of a tree
Polynomial manipulation
8ulti list organization
in"ed dictionary
-!>)rite do3n t4e o1erations t4at are :ein? 1er9ormed on a /ist
Insertion
Deletion
8erging two or more list
Splitting a list
Copy a list search an element in a list
Sort the elements
Determine the number of elements in a list
-8>)4at are a// t4e disadvanta?es o9 Lin;ed ListQ
Gery difficult to insert an element in the front.
Deletion operation is more comple0. i.e.( &ne must "eep trac" of the predecessor of the
node which is to be deleted.
-B>Convert t4e ?iven in9i5 e51ressions into 1ost9i5 e51ressions>
/i2 a-/bSc2Dd
Postfi0 30pressionR /i2 abcSdD-
/ii2 a-bDc-/dDe-f2Dg
Postfi0 e0pressionR /ii2 abcD-deDf-gD-
-,>)4at is deMueQ
!"# $ DATA STRUCTURES 7;
UNIT I-LINEAR STRUCTURES
In Double 3nded #ueue is another form of #ueue in which insertion and deletion are made at
both the front and rear ends of the #ueues.inear De9ue(Circular De9ue.
!"# $ DATA STRUCTURES 7)
UNIT I-LINEAR STRUCTURES
-+>*o3 3i// 2ou insert an e/ement in Dou:/2 Lin;ed ListQ
Insertion at the front
Insertion at the middle
Insertion at the end
-.>)rite do3n t4e :ene9its o9 Circu/ar Lin;ed List
a2 Node access is very easier
b2 Identifying the predecessor node is done easily through chaining
c2 Concatenation( splitting operations can be made easily in circular lin"ed list
"#>)4at are a// t4e a11/ications o9 Lin;ed ListQ
a2 Creating of a tree
b2 $ree traversal
c2 Sorting
d2 8ulti.list organizations
e2 Creation of a polynomial
">)4at is 1riorit2 MueueQ
! 9ueue in which we are able to insert items or remove items from any position based on some
property is often referred to as a priority 9ueue.
"->)4at are t4e :ene9its o9 Dou:/2 Lin;ed List over Sin?/2 Lin;ed ListQ
a2 3fficient deletion of elements from the lin"ed list
b2 Insertion of a node whose &C is specified is efficient.
"">Convert t4e 9o//o3in? in9i5 to 1ost9i5 e51ression <ADB=E<CDD=E<ELF=
Postfi0 e0pressionR !:-CD-D3F
"!>)rite t4e 1re9i5 notation 9or t4e e51ression A-BL<C-DRE=
.!S:DC`D3
"8>)4at are t4e ste1s to eva/uate a ?iven 1ost9i5 e51ression
Find the leftmost operator in the e0pression
Select the two operands immediately to the left of the operator found
Perform the indicated operation
4eplace the operator and operand with the result.
"B>De9ine cursor
$he earlier high level languages li"e Fortran( :asic do not have pointer concepts. $o ma"e
pointer based Implementation( the cursor is used. 3ach cursor node contains the data element and a
position field to store the inde0 position of the ne0t node. !rray is used in cursor implementation
",>State t4e advanta?es o9 Circu/ar /ist over Dou:/2 Lin;ed List
3ach node in a circular list there is only one pointer field to identify the ne0t member in the group(
whereas in a doubly lin"ed list there are two pointer fields
8oving to the first node from the last node is easy in a circular list since there is a pointer pointing
to the first node from the last node.
!"# $ DATA STRUCTURES 7*
UNIT I-LINEAR STRUCTURES
"+>S3a1 t3o adGacent e/ements :2 adGustin? on/2 t4e 1ointer<and not t4e data=usin? sin?/2 Lin;ed
List>
Goid swap with ne0t/position P(befor P(ist 2HPosition P(before P.ist 2
H
Position P(!fter PE
PJ:efore P.PNe0tE
!fter PJP.PNe0tE
P.PNe0tJ!fter P.PNe0tE
:efore P.PNe0tJ!fter PE
!fter P.PNe0tJPE
I
".>)4at are t4e 3a2s o9 im1/ementin? /in;ed /istQ
$he list can be implemented in the following ways
!rray implementation
in"ed ist implementation
Cursor implementation
!#>List out t4e o1erations o9 t4e /ist ADT
$he various operations that can be performed on a list are as follows
Insertion
Deletion
8a"e 3mpty
Find
Print ist
Ne0t/i2
Previous/i2
!>E51/ain t4e di99erent t21es o9 DeMue>
In1ut Restricted DeMue.It allows insertions at only one end of the list but allows deletion at both ends of
the list.
Out1ut Restricted DeMue-It allows deletion at only one end of the list but aloows insertion at both ends
of the list.
!->)rite a routine to return a to1 e/ement o9 stac;
3lement$ype $op/Stac" S2
H
if/L Is3mpty /S22
return Sarray<S$opofStac"=E
3rror/N3mpty Stac"O2E
4eturn ;E
I Khat is 8ulti istX
!"# $ DATA STRUCTURES 7+
UNIT I-LINEAR STRUCTURES
!">(iven t3o sorted /ists LFL- 3rite a 1rocedure to com1ute LFL- usin? on/2 t4e :asic o1eration
ist intersect /ist )(ist *2
H
ist 4esultE
Position ) Pos(* Pos(4esult PosE
)PosJFirst/)2E
*PosJFirst/*2E
4esultPosJFirst/4esult2E
Khile/)PosLJN>MM*PosLJN>2
H
If/)Pos 3lementV*Pos 3lement2
)PosJNe0t/)(Pos)2T
3lseif/)PoselementV*Poselement2
*PosJJNe0t/*Pos(*2E
3lse
H
Insert/)Poselement(4esult(4esultpos2E
)JNe0t/)Pos()2
*JNe0t/*Pos(*2T
4esultPosJNe0t/4esultPos(4esult2T
I
I
return 4esultE
I
!!>)4ere Cursor im1/ementation can :e usedQ
$he Cursor implementation of lists is used by many language such as :!SIC(F&4$4!N
that do not support pointers. $wo important features of the cursor implementation of as follows
$he data are stored in a collection of structures of structures. 3ach structure contain data
and a inde0 to the ne0t structure
! new structure can be obtained from the systemTs global memory by a call to Cursor
Space array. we will "eep a list of cells that are not in any list.
!"# $ DATA STRUCTURES 75
UNIT I-LINEAR STRUCTURES
PART B
). 30plain the implementation and all routines of singly lin"ed list
*. 30plain the implementation of doubly .
+. 30plain the implementation of #ueue using arraysX
5. %ive a procedure to convert an infi0 e0pression a-bDc-/dDe-f2Dg to postfi0 notation
1. 30plain how stac" is applied for evaluating an arithemetic e0pression.
6. Krite routines to implement addition( subtraction M differentiation of two polynomials
7. 30plain the implementation of #ueue using X
?. 30plain the implementation of stac" using arrays.
Q. 30plain the implementation of stac" using X
);. Krite the recursive routine for $owers of Aanoi.
)). Krite the insertion and deletion routine for doubly lin"ed listX
)*. 30plain Cursor implementation of istX
)+. Design an algorithm called 43G34S3 to reverse the lin"ed list. $race the algorithm witan
e0ample.
)5. Define an efficient representation of * stac"s in a given area of memory with n words and e0plain.
)1. Suppose each data structures is stored in a circular array with N memory cells.Find the number
N>8: of elements in a 9ueue in terms of F4&N$ and 43!4 .Find the number N>8: of
elements in a de9ueue in terms of 3F$ and 4I%A$ Khen will the array to be filled.
I9 FRONTS7REARFt4en NU&B7REAR-FRONTD
e/se NU&B7N-<FRONT-REAR-=
Or
NU&B7REAR-FRONTD<mod N=
II=NU&B7RI(*T-LEFTD<mod N=
E5am1/e
For a MueueFFRONT7 and REAR7N or FRONT7REARD
For a deMueFLEFT7 and RI(*T7N or LEFT7RI(*TD
)6. 30plain the routines for polynomial multiplication addition.
)7. 30plain the implementation of Circular #ueue.
)?. 30plain the applications of in"ed ist.
)Q. 30plain the applications of Stac".
*;. %iven two sorted list ) and * write a procedure to compute )* using only the basic
operation.
!"# $ DATA STRUCTURES 71

Vous aimerez peut-être aussi