A Programmer's Approach of Looking at Array Vs
A Programmer's Approach of Looking at Array Vs
AProgrammer'sapproachoflookingatArrayvs.LinkedListGeeksQuiz
GeeksQuiz
ComputerScienceQuizzesforGeeks!
Suggest Practice
GeeksforGeeks
Placements GATEQ&A
AProgrammersapproachoflookingatArrayvs.
LinkedList
In general, array is considered a data structure for which size is fixed at the compile time and array
memoryisallocatedeitherfromDatasection(e.g.globalarray)orStacksection(e.g.localarray).
Similarly,linkedlistisconsideredadatastructureforwhichsizeisnotfixedandmemoryisallocatedfrom
Heapsection(e.g.usingmalloc()etc.)asandwhenneeded.Inthissense,arrayistakenasastaticdata
structure(residinginDataorStacksection)whilelinkedlististakenasadynamicdatastructure(residing
inHeapsection).Memoryrepresentationofarrayandlinkedlistcanbevisualizedasfollows:
An array of 4 elements (integer type) which have been initialized with 1, 2, 3 and 4. Suppose, these
elementsareallocatedatmemoryaddresses0x100,0x104,0x08and0x10Brespectively.
[(1)][(2)][(3)][(4)]
0x1000x1040x1080x10B
A linked list with 4 nodes where each node has integer as data and these data are initialized with 1, 2, 3
and 4. Suppose, these nodes are allocated via malloc() and memory allocated for them is 0x200, 0x308,
0x404and0x20Brespectively.
[(1),0x308][(2),0x404][(3),0x20B][(4),NULL]
0x2000x3080x4040x20B
Anyone with even little understanding of array and linkedlist might not be interested in the above
explanation. I mean, it is well know that the array elements are allocated memory in sequence i.e.
contiguousmemorywhilenodesofalinkedlistarenoncontiguousinmemory.Thoughitsoundstrivialyet
this the most important difference between array and linked list. It should be noted that due to this
contiguousversusnoncontiguousmemory,arrayandlinkedlistaredifferent.Infact,thisdifferenceiswhat
makesarrayvs.linkedlist!Inthefollowingsections,wewilltrytoexploreonthisveryideafurther.
Sinceelementsofarrayarecontiguousinmemory,wecanaccessanyelementrandomlyusingindexe.g.
intArr[3]willaccessdirectlyfourthelementofthearray.(Fornewbies,arrayindexingstartfrom0andthats
why fourth element is indexed with 3).Also, due to contiguous memory for successive elements in array,
no extra information is needed to be stored in individual elements i.e. no overhead of metadata in arrays.
Contrarytothis,linkedlistnodesarenoncontiguousinmemory.Itmeansthatweneedsomemechanism
totraverseoraccesslinkedlistnodes.Toachievethis,eachnodestoresthelocationofnextnodeandthis
http://geeksquiz.com/programmersapproachlookingarrayvslinkedlist/
1/10
4/6/2016
AProgrammer'sapproachoflookingatArrayvs.LinkedListGeeksQuiz
formsthebasisofthelinkfromonenodetonextnode.Therefore,itscalledLinkedlist.Thoughstoringthe
location of next node is overhead in linked list but its required. Typically, we see linked list node
declarationasfollows:
structllNode
{
intdataInt;
/*nextNodeisthepointertonextnodeinlinkedlist*/
structllNode*nextNode;
};
RunonIDE
So array elements are contiguous in memory and therefore not requiring any metadata. And linked list
nodesarenoncontiguousinmemorytherebyrequiringmetadataintheformoflocationofnextnode.Apart
from this difference, we can see that array could have several unused elements because memory has
already been allocated. But linked list will have only the required no. of data items. All the above
informationaboutarrayandlinkedlisthasbeenmentionedinseveraltextbooksthoughindifferentways.
WhatifweneedtoallocatearraymemoryfromHeapsection(i.e.atruntime)andlinkedlistmemoryfrom
Data/Stacksection.Firstofall,isitpossible?Beforethat,onemightaskwhywouldsomeoneneedtodo
this?Now,Ihopethattheremainingarticlewouldmakeyourethinkabouttheideaofarrayvs.linkedlist
Now consider the case when we need to store certain data in array (because array has the property of
random access due to contiguous memory) but we dont know the total size apriori. One possibility is to
allocatememoryofthisarrayfromHeapatruntime.Forexample,asfollows:
/*Atruntime,supposeweknowtherequiredsizeforintegerarray(e.g.inputsizefromuser).Say,thearray
sizeisstoredinvariablearrSize.AllocatethisarrayfromHeapasfollows*/
int*dynArr=(int*)malloc(sizeof(int)*arrSize);
RunonIDE
Though the memory of this array is allocated from Heap, the elements can still be accessed via index
mechanisme.g.dynArr[i].Basically,basedontheprogrammingproblem,wehavecombinedonebenefitof
array(i.e.randomaccessofelements)andonebenefitoflinkedlist(i.e.delayingthememoryallocationtill
runtimeandallocatingmemoryfromHeap).Anotheradvantageofhavingthistypeofdynamicarrayisthat,
this method of allocating array from Heap at run time could reduce codesize (of course, it depends on
certainotherfactorse.g.programformatetc.)
Nowconsiderthecasewhenweneedtostoredatainalinkedlist(becauseno.ofnodesinlinkedlistwould
beequaltoactualdataitemsstoredi.e.noextraspacelikearray)butwearentallowedtogetthismemory
fromHeapagainandagainforeachnode.Thismightlookhypotheticalsituationtosomefolksbutitsnot
very uncommon requirement in embedded systems. Basically, in several embedded programs, allocating
memory via malloc() etc. isnt allowed due to multiple reasons. One obvious reason is performance i.e.
allocating memory via malloc() is costly in terms of time complexity because your embedded program is
required to be deterministic most of the times. Another reason could be module specific memory
managementi.e.itspossiblethateachmoduleinembeddedsystemmanagesitsownmemory.Inshort,if
weneedtoperformourownmemorymanagement,insteadofrelyingonsystemprovidedAPIsofmalloc()
and free(), we might choose the linked list which is simulated using array. I hope that you got some idea
http://geeksquiz.com/programmersapproachlookingarrayvslinkedlist/
2/10
4/6/2016
AProgrammer'sapproachoflookingatArrayvs.LinkedListGeeksQuiz
whywemightneedtosimulatelinkedlistusingarray.Now,letusfirstseehowthiscanbedone.Suppose,
typeofanodeinlinkedlist(i.e.underlyingarray)isdeclaredasfollows:
structsllNode
{
intdataInt;
/*Here,notethatnextIndexstoresthelocationofnextnodein
linkedlist*/
intnextIndex;
};
structsllNodearrayLL[5];
RunonIDE
Ifweinitializethislinkedlist(whichisactuallyanarray),itwouldlookasfollowsinmemory:
[(0),1][(0),1][(0),1][(0),1][(0),1]
0x5000x5080x5100x5180x520
The important thing to notice is that all the nodes of the linked list are contiguous in memory (each one
occupying 8 bytes) and nextIndex of each node is set to 1.This (i.e. 1) is done to denote that the each
nodeofthelinkedlistisemptyasofnow.Thislinkedlistisdenotedbyheadindex0.
Now,ifthislinkedlistisupdatedwithfourelementsofdatapart4,3,2and1successively,itwouldlookas
followsinmemory.Thislinkedlistcanbeviewedas0x500>0x508>0x510>0x518.
[(1),1][(2),2][(3),3][(4),2][(0),1]
0x5000x5080x5100x5180x520
TheimportantthingtonoticeisnextIndexoflastnode(i.e.fourthnode)issetto2.This(i.e.2)isdoneto
denotetheendoflinkedlist.Also,headnodeofthelinkedlistisindex0.Thisconceptofsimulatinglinked
listusingarraywouldlookmoreinterestingifwedeletesaysecondnodefromtheabovelinkedlist.Inthat
case,thelinkedlistwilllookasfollowsinmemory:
[(1),2][(0),1][(3),3][(4),2][(0),1]
0x5000x5080x5100x5180x520
The resultant linked list is 0x500 > 0x510 > 0x518. Here, it should be noted that even though we have
deletedsecondnodefromourlinkedlist,thememoryforthisnodeisstilltherebecauseunderlyingarrayis
stillthere.ButthenextIndexoffirstnodenowpointstothirdnode(forwhichindexis2).
Hopefully, the above examples would have given some idea that for the simulated linked list, we need to
writeourownAPIsimilartomalloc()andfree()whichwouldbasicallybeusedtoinsertanddeleteanode.
Now this is whats called own memory management. Let us see how this can be done in algorithmic
manner.
Therearemultiplewaystodoso.Ifwetakethesimplisticapproachofcreatinglinkedlistusingarray,we
can use the following logic. For inserting a node, traverse the underlying array and find a node whose
nextIndexis1.Itmeansthatthisnodeisempty.Usethisnodeasanewnode.Updatethedatapartinthis
newnodeandsetthenextIndexofthisnodetocurrentheadnode(i.e.headindex)ofthelinkedlist.Finally,
make the index of this new node as head index of the linked list.To visualize it, let us take an example.
Suppose the linked list is as follows where head Index is 0 i.e. linked list is 0x500 > 0x508 > 0x518 >
0x520
http://geeksquiz.com/programmersapproachlookingarrayvslinkedlist/
3/10
4/6/2016
AProgrammer'sapproachoflookingatArrayvs.LinkedListGeeksQuiz
[(1),1][(2),3][(0),1][(4),4][(5),2]
0x5000x5080x5100x5180x520
Afterinsertinganewnodewithdata8,thelinkedlistwouldlookasfollowswithheadindexas2.
[(1),1][(2),3][(8),0][(4),4][(5),2]
0x5000x5080x5100x5180x520
Sothelinkedlistnodeswouldbeataddresses0x510>0x500>0x508>0x518>0x520
Fordeletinganode,weneedtosetthenextIndexofthenodeas1sothatthenodeismarkedasempty
node. But, before doing so, we need to make sure that the nextIndex of the previous node is updated
correctly to index of next node of this node to be deleted. We can see that we have done own memory
managementforcreatingalinkedlistoutofthearraymemory.But,thisisonewayofinsertinganddeleting
nodesinthislinkedlist.Itcanbeeasilynoticedthatfindinganemptynodeisnotsoefficientintermsof
timecomplexity.Basically,weresearchingthecompletearraylinearlytofindanemptynode.
Let us see if we can optimize it further. Basically we can maintain a linked list of empty nodes as well in
the same array. In that case, the linked list would be denoted by two indexes one index would be for
linked list which has the actual data values i.e. nodes which have been inserted so far and other index
wouldforlinkedlistofemptynodes.Bydoingso,whenever,weneedtoinsertanewnodeinexistinglinked
list,wecanquicklyfindanemptynode.Letustakeanexample:
[(4),2][(0),3][(5),5][(0),1][(0),1][(9),1]
0x5000x5080x5100x5180x5200x528
Theabovelinkedlistwhichisrepresentedusingtwoindexes(0and5)hastwolinkedlists:oneforactual
values and another for empty nodes. The linked list with actual values has nodes at address 0x500 >
0x510>0x528whilethelinkedlistwithemptynodeshasnodesataddresses0x520>0x508>0x518.It
canbeseenthatfindinganemptynode(i.e.writingownAPIsimilartomalloc())shouldberelativelyfaster
nowbecausewecanquicklyfindafreenode.Inrealworldembeddedprograms,afixedchunkofmemory
(normally called memory pool) is allocated using malloc() only once by a module. And then the
management of this memory pool (which is basically an array) is done by that module itself using
techniquesmentionedearlier.Sometimes,therearemultiplememorypoolseachonehavingdifferentsize
of node. Of course, there are several other aspects of own memory management but well leave it here
itself. But its worth mentioning that there are several methods by which the insertion (which requires our
ownmemoryallocation)anddeletion(whichrequiresourownmemoryfreeing)canbeimprovedfurther.
If we look carefully, it can be noticed that the Heap section of memory is basically a big array of bytes
which is being managed by the underlying operating system (OS). And OS is providing this memory
managementservicetoprogrammersviamalloc(),free()etc.Aha!!
Theimportanttakeawaysfromthisarticlecanbesummedasfollows:
A)Arraymeanscontiguousmemory.ItcanexistinanymemorysectionbeitDataorStackorHeap.
B)LinkedListmeansnoncontiguouslinkedmemory.ItcanexistinanymemorysectionbeitHeaporData
orStack.
C)Asaprogrammer,lookingatadatastructurefrommemoryperspectivecouldprovideusbetterinsightin
choosingaparticulardatastructureorevendesigninganewdatastructure.Forexample,wemightcreate
anarrayoflinkedlistsetc.
Pleasewritecommentsifyoufindanythingincorrect,oryouwanttosharemoreinformationaboutthetopic
http://geeksquiz.com/programmersapproachlookingarrayvslinkedlist/
4/10
4/6/2016
AProgrammer'sapproachoflookingatArrayvs.LinkedListGeeksQuiz
discussedabove
SeeGATECornerforallinformationaboutGATECSandQuizCornerforallQuizzesonGeeksQuiz.
Category: LinkedList
Like
Share 47peoplelikethis.Bethefirstofyourfriends.
63Comments
GeeksQuiz
Share
Recommend 13
Login
SortbyBest
Jointhediscussion
Anmol 2yearsago
Pleaseaddnextandpreviousbuttonsinyourturorials...
50
Reply Share
Holden>Anmol ayearago
Yes!Pleaseeeeeeeeeeeeee:)
3
Reply Share
erolyeniaras>Anmol ayearago
ditto!
1
Reply Share
RohitJain>Anmol ayearago
yes,itismuchneededfeature
1
Reply Share
typing.. 2yearsago
reallynicearticle...goodwork...
7
Reply Share
EktaGoel ayearago
@Geeksforgeeks
Suppose,theseelementsareallocatedatmemoryaddresses0x100,0x104,0x08and
0x10Brespectively.Thirdvalueis0x108
5
Reply Share
AnsurajKhadanga>EktaGoel ayearago
Yesthirdvaluemustbe0x108andfourthvaluemustbe0x10C
1
Reply Share
DeSaini>AnsurajKhadanga 12daysago
yes,youarerightanshuraj
http://geeksquiz.com/programmersapproachlookingarrayvslinkedlist/
5/10
4/6/2016
AProgrammer'sapproachoflookingatArrayvs.LinkedListGeeksQuiz
yes,youarerightanshuraj
fourthvaluemustbe0x10C
Reply Share
IIT11>EktaGoel ayearago
Yesialsothinkitshouldbe0x10C
1
Reply Share
KanikaJain>EktaGoel 8monthsago
whatareutryingtoask?
Reply Share
shruti ayearago
Shoudnotinthestatement"theabovelinkedlistwhichisrepresentedusingtwo
indexes(0and5)",insteadofindex5astheheadoftheemptylinkedlistitshouldbe
index4,sinceindex5isthelastnodeofthelinkedlistcontainingactualvalues.
4
Reply Share
Chirag ayearago
InLinkedListusingdatasection,howinsertionisperformed?Insert@begin?(asit
insertdata4,3,2,1(i.einreverseorder)).
nhowdoweaccesslinkedlist,usingaddressofheadorthroughindex?
pleaseexplainthisgivingexample.
3
Reply Share
ShwetaCharchita 8monthsago
Wouldn'timplementinglinkedlistsviaarrayimplyfixedsizeallocation?
Czits:
structsllNodearray[5](thatisafixedsizearraydeclarationtocreatealinkedlist)
Verynicearticlethough:):)
1
Reply Share
Vivek>ShwetaCharchita 3monthsago
Butthat5isprovidedbyuseratruntime.Hencethatmemoryisallocatedin
heap
Reply Share
NishuSharma>ShwetaCharchita 8monthsago
NO..structsllNodearray[5]impliesthatwewouldbemaking5ofsuchlinked
listsandeachlistcancontainanynumberofnodes(whicharetobespecified
dynamically)andeachnodeineverylinkedlistcontainstwofields:firstisthe
datafieldandtheotheroneistheaddressfield(aspertheaboveexample
whichu'vespecified).
Hopethishelps:)
Reply Share
http://geeksquiz.com/programmersapproachlookingarrayvslinkedlist/
6/10
4/6/2016
AProgrammer'sapproachoflookingatArrayvs.LinkedListGeeksQuiz
AnnuPurohit>NishuSharma 4monthsago
Herewhatwearecallingalinkedlistisanarrayofstructure
variables.Sosupposewehavefilledallthefiveplacesthenthememory
willbefull.Sothisimpliesthatthisisfixedsizeallocation.Howcoulditbe
dynamic??
Reply Share
AdautaGarciaAriel ayearago
Ilikedthisapproachit'slike"Thinkingoutsideofthebox".
1
Reply Share
GokulRama 3daysago
WhyalltheexplanationisforCandnotforJava?
Reply Share
RajatMaheshwari 7daysago
insteadoftheiruseinembeddedsystem,practically&fromthatimeanincoding
problemshowshoulditbehelpfulorefficient...itwillbegoodifsomeonegavemean
example.
Reply Share
DeSaini 12daysago
thisisreallyhelpful,thankyou
Reply Share
Sahil amonthago
Cananyonepleaseexplaintheuseof0and5index?
Reply Share
Sahil>Sahil amonthago
iamconfused..ithinkitshouldntbe5,itshouldbe4.
Andnowsupposeifiusedthisnodetoinsertmydata.thentheindexwill
changeto1?
Reply Share
amit>Sahil amonthago
6nodes.Soindexwouldbe0to5
Reply Share
SohamGoswami 5monthsago
pleaseaddnextandpreviousbuttonsinthepage,itispainstakingotherwise!thank
you..
Reply Share
Peri 6monthsago
Goodexplanation&insightonarrays/linkedlist&implementingoneviaanother.
http://geeksquiz.com/programmersapproachlookingarrayvslinkedlist/
7/10
4/6/2016
AProgrammer'sapproachoflookingatArrayvs.LinkedListGeeksQuiz
KeepUpthegoodwork!Cheers!!
Reply Share
Adithya 6monthsago
Shouldn'titbecallocinsteadofmallocwhenyouallocatememoryfor*dynArr?
Reply Share
RandeepJohar 7monthsago
Isthecontentgivenisright.Manyincorrectthingshavebeenmentioned
Reply Share
HimanshuMishra 7monthsago
Inveryfirstarraydrawing,lastmemorylocationshouldbe0x10Candnot0x10B.So
addresseswillbe0x1000x1040x1080x10C
Reply Share
AkshAyShaRma 7monthsago
Mind=Blown!!
Reply Share
PrashantChauhan 8monthsago
Pleaseprovidehowtoinitializethisarrayoflistincodeinc.
Reply Share
Deep 8monthsago
Also,oncewedeletethesecondnodethenumberinthefirstnodeshouldnotchange.
Itshouldremainas[(1),1]ratherthan[(1),2].
Reply Share
PrashantChauhan 8monthsago
Cananybodytellmehowtoimplementarrayoflinklist.Howmemorywillallocate
diagrameticallyinheap
Reply Share
NehaRani 8monthsago
"Theabovelinkedlistwhichisrepresentedusingtwoindexes(0and5)hastwolinked
lists:"
itshouldbe0and4
Reply Share
RaAlice 8monthsago
somebodyhelp!!!Can'tunderstandwatrthe2indexes(0,5)??
Reply Share
RaAlice 8monthsago
*indynamicallocationofarray
http://geeksquiz.com/programmersapproachlookingarrayvslinkedlist/
8/10
4/6/2016
AProgrammer'sapproachoflookingatArrayvs.LinkedListGeeksQuiz
Reply Share
RaAlice 8monthsago
whiledoingdynamicallocation,howcanweknowthatnewly(thrudynamicallocation)
formedarrayiscontiguous.
Reply Share
HarmanpreetSingh 8monthsago
ican'tunderstandtheconceptofmaintaininglinkedlistofemptynodesanddatanodes
.
Furthermoreiseetheexamplegivenaboveusesmorethantwoindexesnotjust0and
5.
Kindlypleaseexplain.
Reply Share
RohitSaluja 10monthsago
Itismentionedabovethattheheadofthelinkedlististhenodewhichhasthevalue0
asofthenext_nodebut
Now,ifthislinkedlistisupdatedwithfourelementsofdatapart4,3,2and1
successively,itwouldlookasfollowsinmemory.Thislinkedlistcanbeviewedas
0x500>0x508>0x510>0x518.
[(1),1][(2),2][(3),3][(4),2][(0),1]
0x5000x5080x5100x5180x520
Butinthisaboveexamplethereisnosuchnodewiththevalueas0ofthenext_node.
Sowhytheheadlocationis0X500?
Reply Share
KanikaJain>RohitSaluja 8monthsago
Thislinkedlistisdenotedby"head"index0.(zerothinthearray).
Reply Share
PusapatiRamabrahmam>KanikaJain 4monthsago
ifindex0istheheadthenifweaddonemoreelementitmusthavetobe
addedashead,atthattime,doallthenodesindexestobechanged??
Reply Share
jitinmaherchandani 10monthsago
Addnextandpreviousbuttonsfornavigationtothearticles
Reply Share
MahendraChhimwal ayearago
YuppIamwithAnmol.Pleaseprovideanextandprevioustutorial'slinkforbetter
navigationthroughtutorials.
Reply Share
Zac ayearago
(eachoneoccupying8bytes)
http://geeksquiz.com/programmersapproachlookingarrayvslinkedlist/
9/10
4/6/2016
AProgrammer'sapproachoflookingatArrayvs.LinkedListGeeksQuiz
(eachoneoccupying8bytes)
[(0),1][(0),1][(0),1][(0),1][(0),1]
0x5000x5080x5100x5180x520
butaddressingiswrongforthirdnode.Itshouldbe0x516?
Reply Share
IshanGupta>Zac 10monthsago
Thatishexadecimalnotion.Inhexadecimalafter8come,9,A,B,C,D,E,F,then
againitstartswith10.Asin,8+8=10,likeinbinarywhereadding1+1=10.
Reply Share
Thiscommentwasdeleted.
fadoo>Guest 10monthsago
bc......
Reply Share
Piyush ayearago
Well,iamslightlyconfusedatthepartwheretwoindexeswereusedtomaintainthelist
[listwithactualnodes&listofemptynodes].cansomebodypls.elaborate.
Reply Share
DS+Algo>Piyush 10monthsago
wegottwolinkedlistsnow,oneformaintainingdatalistandotherforemptylist
toallocateordeallocatememoryfast
1
Reply Share
xerosanyam ayearago
Thisarticleisslightlylessclearinonereading.Itisnicethough.:)
Reply Share
Thiscommentwasdeleted.
@geeksforgeeksSomerightsreservedContactUs!AboutUs!
http://geeksquiz.com/programmersapproachlookingarrayvslinkedlist/
10/10