0% found this document useful (0 votes)
3 views

DS Module 1 Solutions

The document discusses various data structures, including arrays, stacks, and memory allocation in programming. It covers operations such as insertion, deletion, and traversal of data structures, as well as memory management functions like malloc, calloc, and realloc. Additionally, it touches on the differences between primitive and non-primitive data structures, providing examples and code snippets for implementation.

Uploaded by

bhsrinivas4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DS Module 1 Solutions

The document discusses various data structures, including arrays, stacks, and memory allocation in programming. It covers operations such as insertion, deletion, and traversal of data structures, as well as memory management functions like malloc, calloc, and realloc. Additionally, it touches on the differences between primitive and non-primitive data structures, providing examples and code snippets for implementation.

Uploaded by

bhsrinivas4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

TNTRODUCTION T

DATA S TRUcTURts
. ohat s iy
Disus te upxatation
linou algontm
n
elenent

ollabrng om a lhear avray


A, nea

pe. These olata itens, ae


lacahoy

a iea?
daBahpe aray-nanni (iie-q-aTy))
Ant alst

Reprtantation ihe uay in


mamoy
Considn the above
tqntag da clatatioo ea a

int als;
The pttodal eprentatipn

a hea tart
0, which jio the lowa bo unddr,

Thus, tfe umbe elemurit


erunt

(kolag Aepreintativn the above


1000
aray
Can bo
base adess

by the foliouw g tgue


Jhe ocettbn
the mcu o the

wod

b low bound

Su the' ocabbn kound


Then

Loc al- tooo + *(3-9)

eleent. nto hear

Skpi : start
Stp.2: Raad pos, elam.
element
a(i+1]: al:);
4: Dnset the eleent at th
Jfep
a(posj olermj
Skp-Si Tacvcmnt the e the atay
n:nt|j

S. Deleteng elemment Jom tuu hear ary'


an
aeprli Stat
2: Read pos.
he elento the arty o the ft.
Step-3: Moue

aliJ aCrtJ;
3 elenent in the ar ay i
'4 Decnment the

St
&. Daota blo Jtatii and Dynamt nenoy alloa
moy alloahbw funcim
MA
Statie N,A Dyrame
o allocated while
Menoy
program Run- me allocat
bme aoat
Can be charigd

. Ex: Arvaiy
DMA Fnchms:
() MALEOCt):
fusneg a blok
his hunchion
tte
block b atoeat roke
Bue
a NUL value.
t utung
allocation then

yntar: maMoc(e);
ptr (data- ype a)
ptr the voálade ty daut
data
dota.pe è any basic
dato ypc
stu ia the umba byte the block
mony
ptx (nt *) maloc(D);
Alocats Hock

) CALLOtc):
locks
This tunebom alotaln space for: mulbpA
menong each and. tnlhial'es. al g
to holo).

uns a NDLL vate

yntar si);
ptr- (data-type ) caloclpb.
bohe n: the nembe o locks of munsy to be
aloatid
block
Siee si2e each

ptr fnt *) calloc (o,e; sia


4Uocats I0 bloks memony each

esiy
eatbocto the blok nmoy hat
" This

kun c i .

pont o he
when
a NULL value and Jhu old block Aenars unhangad

ptra Cdata-type the blolt


str |chay tmoullo ( io) ;
stpysty "lomptea 2
(gt, );
sty (chay )ealloc fewene and Engheerig

prsiousky
) FRE EC) alloralod
Thes tunion Re
mallocC, (alloc (
yntar'

ptr - (int x) malloc (rre g(mt))


free(pt and CALOC :
bati blw MALL DC
3. Dhen Callocc)
malocl)

ablotato nly

Syator Syntar
iihalie Jnihaliy aloated mumoy
"-It - ddou not
vouo
'Contis
pt malot (ro); allocatid to
pO byteso

Totel byes: (o byes. Total mem ny


f. Explain REALLOC
ma coo REALlbC
proq ra mJhowng, sa

The reallor () unehons memony by


eallocats
allo cati d blocks q memony.
modityng aaady allocatad y
t resies the Memoy hat pieiouwly
Is Aeloc C) able do the
new block
to t e staut th
it etuns a
wnabk to do te

NULL value rd He old block Nemains wnhanged.

Luntaz' *) ealloclpty rssi);


ptre (datatpe
7Explan Each to
Yaogtam shog Urag g Mao REALLOC:
H meuoe stdio.hs
# melud<stdlibh)

*dayine REALLOC(P n, byp)


P (type hllefsg;

vad maih ()

st (char matloc (10))


gtrcpy(rt, "Compitr
REALLOc sti, o, éhar
Su'enu and
^lomquar

srahgs Coreputn
Stnng Computn deimca and Engiheehy
sha ck
5. Dinu Stack. Disus how to
o data suchue
Sen: AStack s a specia dyp in head
(Lhear S) in wich the lment

st
the barne end. S t ennt to be
this ti last
to be Deled Out.(LIFo)
Ihseited is the

Stauks whg Dyramte Arip: s


Rupaucntng the
Let s ke a ponte
and 3IZE js the
the stack
hich
Btalt
stack, wehet
an eleunt to the
wtutheehee
Stack.
SI2E -l, then the tatk s

mplementd in cod''a belo


OKT
Condtion

(topSizE-)

Contol, elemeno can be


Jasutd
The code
{ (op:: SiZE -1)
pnht( Statk in Fl, Updlate srze and hsnt

SYZE

the aboe
conditio faio, item canbe hsetd
in the stack stack
Dhe londii'on s t a , ten st the
Aneasecd Ae aeallot( kunBon and then the
int te stack.
To t Top mst jnesomaled

top top tl;


ieted at the op the stalk as
item
folous:
s[top] : itemj
tunctin'
Lotd push )

SZE++j
s=(nt a) neallor(SIZE «

sE4t top: tan


6. pib pncqvam mplement Stack
State and dynan'e Qrag.
Stacks wsing staht ray
impement
ncude <stdio. h>

dene STACK-SI2¬ -5
#
int top

B(top STACE-NZE,-)

ehn

popl)
t

gehin tem, detted:


eid diplay C)

pnH(" Stalk b
thnj

3
void mauh ()

int choia)
top:

pnhl"). Push 9. Popn");


pnls. Duglay . Exit \n" n;
prht|l"E ntar yo hoia:
bwiteh (hoie)

pnnt, ( Eda the itbm to be nsetid: ln

break;
ntetetttd
iem popl);
nglyin"

brtat)
Cal-3
dis ptay);
brtat;
dalaut: uit(0;

Paogam wng Dynamt Aay:


h
# helue cstdib

o'd

4 (top= S12E-)

pront ( stauk by 19;


top: top t S

nt poplimt bop, mt f1)


iot itemdeletd

: s[top;
item- delt1d dutid
tuin itam- ; .

play (nt top mt sI)


nt dis
mt ij

pront("Cortent
woid mah t)

at top :-l}
mt #a3 choia)

torli)
poht("4. fush op\
pont ("rta You Choia:"
Swittehlchoice)

Case I:
prmt (" Entu the item to ba.

breat j

sBem 'pop(ktp s );
item)

Cae 3:

brtab,
3 deluut:
1. Wtt a C prog Tam to cheek for a palindoe
gtacks.
| ihud <stdio.h)

int is- palin&vorne lchar str CJ))

chas s[2o, stk-itmj

7or Ci': o; i stilenlstY); it+)

tor (i-oj i<strlenlsty); It+)


stk- tem: st[i;

void man C)

char str (90);


int

Yag is-pabidme (st),


P%The nof aa palnd oom/[n
nof
Palndaome\

f.4 (statiz avay


pain ta Clasn iatong
9. Deline Data sStucue
Pata Stuctwe Cperati.
S voith karples and
Sol9: The dogital
model a
o mathema'cal peutul
data stnictuie
data

Clastkcatin: ito primthe


Data s t u e s au
and
p's.
() Pimi've DS: real,
Basic
Such as ntege,
data typeswndr pamihve DS.
COnme 1choiatlutthet cannot
Consist
These data y shpl
be dolel. ene,t y

Non- amitue Ds:


(Ö)
The bst ame tor a nom-pomitie Ds ia puhg
numbe.
a tomler Gaps ae alL
Stack, Ruetes, TAees
Anked ito, Nepammite Ds,
Non- Prmihe DS au
Non-neo ps band on. stuh . rcumt,
olata
Qunes
Stacks
sti hte
Aays
eaL
)Pomitve
-Pönihue
Stuetie Data
1louchaut!
Tes
Liheen
p No-n ndu
debton hsekon The
s'he hyinot sdala
oid.
aanged not leninb
au ito J4
h
is Non-khea:
D ADs, b)
hea non- be tosaid
DS. Leor
AMag
Stacky
an
d sto, Lihkedtauhin,
elr cony Queeey
data
u Ds, lea a In
ital in
amangeed st.
element
a
the
o DS A DS: kiheag (4)
taicd
Data sttue OpeialiospS: is proused by
The data oputing
ceztain opuatts.
bs opesatno,
trequenty uid
each tcod eratlly
: Tranrsing Accenngin that cord mey be prvcesed.
cutain
hat
e hecord wptk
the loCat
Q. Seachig Ynding
a mone conoitos.
ohch
e cord to tuDS
rew
3. Tgeting Adsig DS.
CoTd om he
Rernovg
the
S. Jorbng Arranghg Jone NAME
NUMBER
somo N

the ecorcs
Combm g
Qre
more opyatios
kit ieah tör the, loat?.
a eoeo, hushe must
·the eeord.
LOite a C program fa C lor -te
cpurattu:
n eemnt
In teutng lement
Deleting an

elemens
Diaglay Array
&t.

+ inuole <stdo. h

int isst (int iem, nt int o ojnt pos)

(pos>Alpos<o)
pnnt[" Invalid porlko ln

a[11J: a

yehn n+lj

iat deet (iat ac), tat pos, tot n)

prnti("Invaliol positan \n"}


a[ alit

etn n-lj

votd dibpay (iot alJ, tnt n)


6lemento are: \n");
The arTay
for(i:o) icnj it)

oid man ()

choia, n, tem, pa

pnint("1. Inut
pont"3. Diapayyouu choia\n
tu
&witehlchotu)
eritlo
de<aulti
diaplay(al
n) ),
3!
Cax
breat
n, delee
pa(aC), n:
n"))positioo: the Entu PL("
Case9
break;
po)) 0, Crt,aem inut n:
pokn:
"\r the Etu B"
o be lenent PB"Entu
the
Casel:
blw uttwus and Unin. fhow

kkanpus a both
Stuitwis Unions
Degired by he teyloodl
kyword
unio
Sluct
shae Q comon
Stutues alocats Unions
memoY
spa ca bos al
Ahovagmembs
oreuyy Smalle emoy
Stuetus oecY
dargu mamoy pa membe a wbn
Can acces l
Can be Qceemo at a the.
te embes o the
Stsute t a e
Aame or all
Addrs
Stu c e wion memheS.

(0 Steeus
t mcede Kstdio.hs
Stuet tucent
gtuent sl;
Pnt marts sl.
chal
sl. peacant

BCarada: 1sn sl.qad}


3
9p Maks q0
qrade : A
Perent = q0.00OO00

() Unioes!
vold mnh C)
t meude <tdo. h
union Sbuoden t shuolent sl
sl, ma ts = 8s
nt markj P"mabs = /.dn' sl. mark
char qrad. :"B"',
ttoat pesant
sl. perent - 85

qrade
Percent S.00
chaatu oluncd by'lob'
t4lmimatd by null

Stnr Randing frchons


) stren():

tot strle lohar st C);


the

'o' erept
Ths,
stren():
dmy sten(chorstr(3)
tot

int izo)

ittj
ehn i

skzegy tol str(), char go 2 U);


the tontento stng sta
to sag tnl, mchisting te Vo'
be greab Tian'
sty! must
Thus, the sie q stng st
a equal to the
st
hen the contnt
t lae Lost.
Lortents

shpy:
mstry(char stlC], kas' st
vold

vokile (str [] != )

(ti)sttat (): i
strmg ntr ho
the contvt
tunctions cepie
the

Tue main condhon n wt


the ontento
Stol +str2
Sipntar:
stcat (ehar stal(J, chor str 2 ;
Yunctinn,
tt[, char sh?[0)
yoid my-shcat(char

joj

stra[i Yo'.
3

Smtar: fat
the conen to
This funchions compas
oith the 'rst chaya ctu. o
The companDin bugihs
the
conhhs h the cRresonding
The compauston
no,

Nsty 0.
tuntion.
strmp(ehar stol), har tt ()
jnt my

ohile (ttr}Ci str2 ))

'\o')
breat}
ittj

rehurn str I[r]- str2CiJ;


NatnX How to panse
14. mataik
Dejiu pare algoaitntnctg to tanose
matik

A matix contaningCalled
manysparse matnes.
hon-22ro ntties are

Kpresntation a spare Matnìx:


a mix Can be
tlemnb
<rowo val.
malno tan be thex
Thus, <paase
and -D asay as

# dulie MAK-fERNS lo1


stuet

fat ow)
int val}

TERM a(Ac TERS


matnx.
Collo)

22

15
witt
The abou matdx alor
The
oe col pofitors
hay as folloer.
Col val
Row
alo) 5 Rowfo]

3 40
fowl
11:
22

als) 3
alc) 3 3

a 4
a3] 3

ontuns all
* hee ow

not pto
Coideled in his epreentat
tund" to traupose pa%e mati
TERN b0) n TE{M The
vold transpo (TERN aC), dato typ
monl)

alo).ow [o). ol

a[o].va, jtt)

b[K].mw alj. col


b[kJ. Col *
KEJ- vad a
:
val
ktt)
3
PoINTERS AND DyN AMIC MEMOAY
AuocATlbN
PoNTERS:
Pomter van abe tat hotd the addres anot
varlabe, ·e, the acbua value Q

addres
rmemong
The to mort mportant oitt the potr

k the addres apu~tor)


* ( he dijuancing/ ahdiàs chiÝn ope rator)
pomtea in declaed

ntegu vauabe and pi

Let oid

hebw the adds aai'gn t a


the vue pi.
A value
) i:

Dn both the the ntegu l0 u sod as the


value
vauabe pomtu
(a)
pokt null for tyt to
bollowg The
C
false. intuputd
n Wed
(o). the
oton. ol2eno.qetsntegu
no A
binto pomter:
15. Dfine Ponts How to de leu and mihal 2e
ypomts?- EKplain tojth eampo. t the aduantag
arays k plain oid' pomta
Sol: Ponter 4pcepl pe vaiabu hat holds the
addren anothw aabu.

2 important opctos ed wt pomts a:


() (thu addy
(0) *(The duepencing opraa
Declarat:
data- typ # ptr-vanablo name)

pour van'ablb dota- tyx ht.


Heu ptr s

Jnih'ali20tion: aoe dctaatin below:


Congiclu the

an mhg vanabe ptr » a porntkr


Here
vanabe thot pomb the ntga.
Now,
ptr i

?vaue Can be

In both tho ns, vaue o i lo.


A ul pomtu doc not
kay the htigu eeotò)

mtopreid bale
to test

Blp::NULL)

viabe

Advantagu 4 memoy alloca? t.ey


Pointae allow dynamie
allotated at the tun hhe
an be
nuec. This
based On spe cae ad they hane
not possible' ar ay, tie
gi2e det (arcd at tis compla
the
Pointy enalbe Stuctus lation and maniputa"
conpler data
te, Thuse
mpementi usng ar tays alou.
diktiut to
fonts enabe
vau o t
to th vaiabu within

the vale cutido te unton, This ho


Kfrint fhan
caluw,
Void Ponter:
A wid pomtin a pornu vau'abe whith has votl
to
data type,
special ype pomtu wheh ponto to
Vauiasa data
Sotax delarat^:
votd p;
Sne a vaarable (annot hae oid data hy, thuu,
the no dlata and lanot de
deryone.
cha h 'A

P"chaaetu: 7.d\n *charÈlap))


koite the ast tanspoe agonhn trargpoe
16. giuen spas matix.
the

Ous
1. Reverse the su 4 matix by ntschang
coumns.
bo].ow a[o]-col;
b[o]. col = a[o).ow;
blo]. val alo).al
&
tore eleunb
L[k).
b[]-col
aj]-valj
3. Kepeat slep until al e non- eo elementb n the
mat i
a the nef
Inumunt the yalue to
ay

s. stop
Studunt 4
pelcant, sloat
gracdj chel
masts,
stuet
the allows
typu, data the Q'
mort
grad
picentj toatchor
at
maxts
rtudent stuet
dggunt
wrdua
pmgdada mlsjpl datu
qroptypu
sam vanabls
of
bype mmpe mSt the H
c swsedAncle Stu 0)
enbs: orth
typce. data
nplementation Erglain.
ternal Stet the Ddinn 14.
utea type Explain
044
3, shueue fantw! alloatb
dynamally al
membes o He s t e
and acces th
m ony
stnut Prson AplSon pt (tuet Pescon)
per son pt mallor(si2)
4 Netd Stuctses:
A tmucture . embidded
data
compl
Stuet

nt monthj
int day
geaij
Jdatj

ohar name l
dati dob
3persony
Jntuunal Jmplemetat ion Sthutws:
The
mmbes th stucue.
dufined
Considu the Atuaws.

puon

int ag)
doubu 4alay'i
Jo a: §"RAHUU', 42, 35000} )
The pactonal epresn tatin o how the atoe Valuss ae

helow:
Sine
1

4alary 3 so oo. 00

The V a s The hucung addes


Jo eah'ons t

detohibin
hat h staaaa adce membu name
Adds

Add. agt
Addn stautig adas +
kalay
LOO7 t 4

Add.salay
Jtaek. LIAt and Enplaun Naous opsatibm
stat ovfow ata ck
udonow oncinu.
data
dol?: Astalk a

ohich an leent
and deltd hom th same enel.
last nt wtd
deetud Out (LIFO nethod)

Staek Qpucctions
can be
The vOlbw opacinu that
stacks
) Pah 0puatim:
lument to a Atack is talld push
Tnsing the stack
opuatiori item Can be inseted
mtu
tte
6ne
tu ia meeted Am
the
t a tine and
Jtaek.
ito the ttaCk,
ting an elumt
mst cheek ohethe a staek ww
an elemud into
to set ovfow.
Awulti in stack be
the staek ad top
Let S2e
the top q e Atek.
ben te tack tull loefleu)
:siZE -,
Code flous:
ainglenend
toptIj :top
ovalow'; Stack PC"
-)sI2E topz
) int etop,push(uit void
(optona): Ancton
witig ky
lement the Then
thedemut,
an
t be
must
tn
Ovuftow! ("tak prh
Size-1) Ctopz y
po operatn.
puting an elemunt
peraton.
thu the sack
dement itn is oeltd hn
Bdu dltig an lt m
the stact
eheck vohethe
daate item n an empy tack
stack wndupow.
en the coole
This conditui ke anplemntd

tn he staek is

y (op - )

etunj
the stack, a
To deate defehed and
Valable called
the ttom that
jbem dlitd.

Lasly, the valu


turdi Cophibna)

B(Stack Unduflow
3ind itomdeleted

vetan itemdltd,
( Dia play opuátion: the
al t e contnts
ephation,
stach
daplagyd. a stalk, cne must
Beydu diaplaying Conlent enpy oherwi,
check ohethA he stack

t reno in ndow ondtin


ohethet stack io epy
The code to cheet

Undetlao'
Then tsed
a Back, udl it eah te top valuu

The cooe tolouws


i<s top; it)
tor lio; i<z

tunction: (ogtionas
voidl display (nt top, nt st0)
top-)
PC"staek wrollo);

The ontnto sta.ek are'n"


lor (i0, i <e top; it)
tl"zon", st);

3
to conit
functim and
6) Tnyx to Postfx

Step I: Staut
Stap 2: Read i Jo sC), top, symbol
Inikolie top-l j
j0;
Stap 3: for each

ohile( F(sltof) >Gaymbol)

s(tttop] sunbalj

Sey : fop elmnt am otat l any) and fauto


ohile (sttbp!-'#)
postt jtt): s[op-J
(ags)) (ioquhsg
<
4)xod c-dags

(aj4+]9 foquhs
) Zner bpreltr'

). Stast

pet

3. Reves the
streln,
4. tor each

greatu preden
preyex [+tj):s(top-2 than mut synl

top -- Mpop }rom stak.

4ctual
str rer geg
6. End
Huntn:

char

strv(n
7or(ieo, i ctrlenlnt), itt)
| - yin
ohle (FlsCtoy) >
pron:fp nPop fromgtack .

S[ttop symbolj push to sta ck .


btack.

3strfprt),
sygjtt:s(tp J

strrer prf),
and multt
odo you apent sngle
dinunal
allocat9
Sol": Dhenaional ameysi
one-dienslanal aiay
Nemdy Macco
mallo hunchon,
httqens
wing art dyoaay
allocate menony to
ven belbw:
ng maloc
int
MALLOC-INT(ot )

X: (iot ) malloc (n *feq (mH);


C*NULL)

ecitlo);

3
ntcgtry th funet'on MALa INT)
To allocat memYy kor
s calhd the s t this furet'on co ehund to
a pomka vaable p e code
Junk vae

P: MALLOc- INT(S))
2
" Similaay nemoy Can k alotaled to Koat, cha
and doube voaiablu
voiasw by wsng tloat, chas and double

Muti-Damunsional Asvays: (-5)


two oays to allocate memoy
dyrarmially arrayo. Thy arei

) To allocate ponter:
Consid an aray oith xt x
3 vOus,thue
alloated to 3
xt]. The be
memoy Can
mallo () folloui
MALLOC ( ows ot); 3rs
ro ws 3
iey MALLOl, 3, t *); x
eech gw wotth spedfcd
( ) To alloeate memoy to
coumn: each
ortk 3 ows,
Consio the same aray
memoy can be
het the
S colum. Thes
haty
allotatd
ound

malloe 0 as follbusi
MALoc(*lo],6, o t
MALLOc (xC1],s, hte);
MAL Loc (x(2J, s mt)

abone hwnbn org


tunctimi
itJot int ij
for jo**X)
t int
MALLOC make MALLOC
li=oj
2d
j (x, array(mt (Kf),
0uj 20ws,
col,
i)
nt); nouo, int
nt
ht
col)
Sot #neuole
<abb. hSoln:
heucectdb.h motices
7or ini,t j **) iot
cratarray 3 program
Onih a
MALLOC
7orCi-o;
i<rou
itt)
Citor *oj RC"Instint
Memoy ") thot
jeo; MAOC(x
iK (x, ae
j<outj OS, (int
colej creatid
), o
jtt) it) cole, int s, o
A); nt penkom
int); col9 dynamially
adation
aclolion

two
maun
vad () vold void
PkC ¢*C)ntt*bnt**a}ot
add.orray mead-array
t9 Entu 3
the tot (0,
Sa **a,
iot Hows,
the **b,
a)\n; bot
mat nt
**G oy
nt
ous
iht
ob)
L
add(a, C: P&l Pl" P"Entu a=
dinplay-read-array
mak Entu Matir mak-
b.c, oayla
arvayrows, th arsay
TowS, A:(a, the
elemento \n"; ows,elnent lo
olo)
rous, b)!,
ob; co)
o co)
&i\n')
Natnk Mati

A:\n");
int 3
stlen );m else
pat.mato fosj0)
utn k
G33n) breatj
int Borhhue itt; i:E)
pl, j< Cprogam
wnt n)jtt)
ttgtet
t) to
seueh

pattn
Veln'p
\a; poihon
tound at
found
\n" not
tk); stnhg:
pas: Itg
t);
pat.matulp.
8,
por(p tert
Pottun
str. the
Entu PC"
tag -etin
C)
man
vord PH"
ot
3

You might also like