ESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues ...
Traversing the Linked List - dsauet.weebly.com · While traversing the circular linked lists we...
Transcript of Traversing the Linked List - dsauet.weebly.com · While traversing the circular linked lists we...
• Traversingthelist• Insertinganiteminthelist• Deletinganitemfromthelist
TraversingtheLinkedList
Let us assume that thehead points to the first node of the list. To traverse the listwe do thefollowing
• Followthepointers.• Displaythecontentsofthenodes(orcount)astheyaretraversed.• StopwhenthenextpointerpointstoNULL.
TheListLength()functiontakesalinkedlistasinputandcountsthenumberofnodesinthelist.Thefunctiongivenbelowcanbeusedforprintingthelistdatawithextraprintfunction.
TimeComplexity:O(n),forscanningthelistofsizen.SpaceComplexity:O(1),forcreatingatemporaryvariable.
SinglyLinkedListInsertion
Insertionintoasingly-linkedlisthasthreecases:
• Insertinganewnodebeforethehead(atthebeginning)• Insertinganewnodeafterthetail(attheendofthelist)• Insertinganewnodeatthemiddleofthelist(randomlocation)
Note:To insertanelement in the linked listat somepositionp, assume thatafter inserting theelementthepositionofthisnewnodeisp.
InsertingaNodeinSinglyLinkedListattheBeginning
Inthiscase,anewnodeisinsertedbeforethecurrentheadnode.Onlyonenextpointerneedstobemodified(newnode’snextpointer)anditcanbedoneintwosteps:
• Updatethenextpointerofnewnode,topointtothecurrenthead.
• Updateheadpointertopointtothenewnode.
InsertingaNodeinSinglyLinkedListattheEnding
In thiscase,weneed tomodify twonextpointers (lastnodesnextpointerandnewnodesnextpointer).
• NewnodesnextpointerpointstoNULL.
• Lastnodesnextpointerpointstothenewnode.
InsertingaNodeinSinglyLinkedListattheMiddle
Letusassumethatwearegivenapositionwherewewant to insert thenewnode. In thiscasealso,weneedtomodifytwonextpointers.
• Ifwewanttoaddanelementatposition3thenwestopatposition2.Thatmeanswetraverse 2 nodes and insert the new node. For simplicity let us assume that thesecondnodeiscalledpositionnode.Thenewnodepoints to thenextnodeof thepositionwherewewanttoaddthisnode.
• Positionnode’snextpointernowpointstothenewnode.
Letuswritethecodeforallthreecases.Wemustupdatethefirstelementpointerinthecallingfunction,not just in thecalled function.For this reasonweneed to sendadoublepointer.Thefollowingcodeinsertsanodeinthesinglylinkedlist.
Note:Wecanimplementthethreevariationsoftheinsertoperationseparately.
TimeComplexity:O(n),since,intheworstcase,wemayneedtoinsertthenodeattheendofthelist.SpaceComplexity:O(1),forcreatingonetemporaryvariable.
SinglyLinkedListDeletion
Similartoinsertion,herewealsohavethreecases.
• Deletingthefirstnode• Deletingthelastnode• Deletinganintermediatenode.
DeletingtheFirstNodeinSinglyLinkedList
Firstnode(currentheadnode)isremovedfromthelist.Itcanbedoneintwosteps:
• Createatemporarynodewhichwillpointtothesamenodeasthatofhead.
• Now,move theheadnodespointer to thenext node anddisposeof the temporarynode.
DeletingtheLastNodeinSinglyLinkedList
Inthiscase,thelastnodeisremovedfromthelist.Thisoperationisabittrickierthanremovingthefirstnode,becausethealgorithmshouldfindanode,whichisprevioustothetail.Itcanbedoneinthreesteps:
• Traversethelistandwhiletraversingmaintainthepreviousnodeaddressalso.Bythetimewereachtheendofthelist,wewillhavetwopointers,onepointingtothetailnodeandtheotherpointingtothenodebeforethetailnode.
• Updatepreviousnode’snextpointerwithNULL.
• Disposeofthetailnode.
DeletinganIntermediateNodeinSinglyLinkedList
Inthiscase,thenodetoberemovedisalwayslocatedbetween twonodes.Headandtail linksarenotupdatedinthiscase.Sucharemovalcanbedoneintwosteps:
• Similar to theprevious case,maintain thepreviousnodewhile traversing the list.Oncewefindthenodetobedeleted,changethepreviousnode’snextpointertothenextpointerofthenodetobedeleted.
TimeComplexity:O(n).Intheworstcase,wemayneedtodeletethenodeattheendofthelist.SpaceComplexity:O(1),foronetemporaryvariable.
DeletingSinglyLinkedList
Thisworksbystoringthecurrentnodeinsometemporaryvariableandfreeingthecurrentnode.After freeing the current node, go to the next node with a temporary variable and repeat thisprocessforallnodes.
TimeComplexity:O(n),forscanningthecompletelistofsizen.SpaceComplexity:O(1),forcreatingonetemporaryvariable.
3.7DoublyLinkedLists
Theadvantageofadoublylinkedlist(alsocalledtwo–waylinkedlist)isthatgivenanodeinthe list,we can navigate in both directions.A node in a singly linked list cannot be removedunlesswehavethepointertoitspredecessor.Butinadoublylinkedlist,wecandeleteanodeevenifwedon’thavethepreviousnode’saddress(sinceeachnodehasaleftpointerpointingtothepreviousnodeandcanmovebackward).
Theprimarydisadvantagesofdoublylinkedlistsare:
• Eachnoderequiresanextrapointer,requiringmorespace.• Theinsertionordeletionofanodetakesabitlonger(morepointeroperations).
Similar to a singly linked list, let us implement the operations of a doubly linked list. If youunderstand the singly linked list operations, then doubly linked list operations are obvious.Followingisatypedeclarationforadoublylinkedlistofintegers:
DoublyLinkedListInsertion
Insertionintoadoubly-linkedlisthasthreecases(sameassinglylinkedlist):
• Insertinganewnodebeforethehead.• Insertinganewnodeafterthetail(attheendofthelist).• Insertinganewnodeatthemiddleofthelist.
InsertingaNodeinDoublyLinkedListattheBeginning
In thiscase,newnode is insertedbefore theheadnode.Previousandnextpointersneed tobemodifiedanditcanbedoneintwosteps:
• Update the rightpointerof thenewnode topoint to thecurrentheadnode (dottedlinkinbelowfigure)andalsomakeleftpointerofnewnodeasNULL.
• Update head node’s left pointer to point to the new node andmake new node ashead.Head
InsertingaNodeinDoublyLinkedListattheEnding
Inthiscase,traversethelisttilltheendandinsertthenewnode.
• NewnoderightpointerpointstoNULLandleftpointerpointstotheendofthelist.
• Updaterightpointeroflastnodetopointtonewnode.
InsertingaNodeinDoublyLinkedListattheMiddle
Asdiscussedinsinglylinkedlists,traversethelisttothepositionnodeandinsertthenewnode.
• Newnoderightpointerpointstothenextnodeofthepositionnodewherewewanttoinsertthenewnode.Also,newnodeleftpointerpointstothepositionnode.
• Positionnoderightpointerpointstothenewnodeandthenextnodeofpositionnodeleftpointerpointstonewnode.
Now,letuswritethecodeforallofthesethreecases.Wemustupdatethefirstelementpointerinthe calling function, not just in the called function. For this reasonwe need to send a doublepointer.Thefollowingcodeinsertsanodeinthedoublylinkedlist
TimeComplexity:O(n).Intheworstcase,wemayneedtoinsertthenodeattheendofthelist.SpaceComplexity:O(1),forcreatingonetemporaryvariable.
DoublyLinkedListDeletion
Similartosinglylinkedlistdeletion,herewehavethreecases:
• Deletingthefirstnode• Deletingthelastnode• Deletinganintermediatenode
DeletingtheFirstNodeinDoublyLinkedList
In this case, the firstnode (currentheadnode) is removed from the list. It canbedone in twosteps:
• Createatemporarynodewhichwillpointtothesamenodeasthatofhead.
• Now,movetheheadnodespointertothenextnodeandchangetheheadsleftpointertoNULL.Then,disposeofthetemporarynode.
DeletingtheLastNodeinDoublyLinkedList
Thisoperationisabittrickierthanremovingthefirstnode,becausethealgorithmshouldfindanode,whichisprevioustothetailfirst.Thiscanbedoneinthreesteps:
• Traversethelistandwhiletraversingmaintainthepreviousnodeaddressalso.Bythetimewereachtheendofthelist,wewillhavetwopointers,onepointingtothetailandtheotherpointingtothenodebeforethetail.
• UpdatethenextpointerofpreviousnodetothetailnodewithNULL.
• Disposethetailnode.
DeletinganIntermediateNodeinDoublyLinkedList
Inthiscase,thenodetoberemovedisalwayslocatedbetweentwonodes,andtheheadandtaillinksarenotupdated.Theremovalcanbedoneintwosteps:
• Similar to thepreviouscase,maintain thepreviousnodewhilealso traversing thelist.Uponlocatingthenodetobedeleted,changethepreviousnode’snextpointertothenextnodeofthenodetobedeleted.
• Disposeofthecurrentnodetobedeleted.
TimeComplexity:O(n),forscanningthecompletelistofsizen.SpaceComplexity:O(1),forcreatingonetemporaryvariable.
3.8CircularLinkedLists
Insinglylinkedlistsanddoublylinkedlists,theendoflistsareindicatedwithNULLvalue.Butcircular linked lists do not have ends.While traversing the circular linked listswe should becareful;otherwisewewillbetraversingthelistinfinitely.Incircularlinkedlists,eachnodehasasuccessor.Notethatunlikesinglylinkedlists,thereisnonodewithNULLpointerinacircularlylinkedlist.Insomesituations,circularlinkedlistsareuseful.
Forexample,whenseveralprocessesareusingthesamecomputerresource(CPU)forthesameamount of time, we have to assure that no process accesses the resource before all otherprocessesdo(roundrobinalgorithm).Thefollowing isa typedeclarationforacircular linkedlistofintegers:
In a circular linked list,we access the elementsusing thehead node (similar tohead node insinglylinkedlistanddoublylinkedlists).
CountingNodesinaCircularLinkedList
Thecircularlistisaccessiblethroughthenodemarkedhead.Tocountthenodes,thelisthastobetraversed from the node marked head, with the help of a dummy node current, and stop thecountingwhencurrentreachesthestartingnodehead.
Ifthelistisempty,headwillbeNULL,andinthatcasesetcount=0.Otherwise,setthecurrentpointertothefirstnode,andkeeponcountingtillthecurrentpointerreachesthestartingnode.
TimeComplexity:O(n),forscanningthecompletelistofsizen.SpaceComplexity:O(1),forcreatingonetemporaryvariable.
PrintingtheContentsofaCircularLinkedList
Weassumeherethatthelistisbeingaccessedbyitsheadnode.Sinceallthenodesarearrangedinacircularfashion,thetailnodeofthelistwillbethenodeprevioustotheheadnode.Letusassumewewanttoprintthecontentsofthenodesstartingwiththeheadnode.Printitscontents,movetothenextnodeandcontinueprintingtillwereachtheheadnodeagain.
TimeComplexity:O(n),forscanningthecompletelistofsizen.SpaceComplexity:O(1),fortemporaryvariable.
InsertingaNodeattheEndofaCircularLinkedList
Letusaddanodecontainingdata,at theendofa list (circular list)headedbyhead.Thenewnodewillbeplacedjustafterthetailnode(whichisthelastnodeofthelist),whichmeansitwillhavetobeinsertedinbetweenthetailnodeandthefirstnode.
• Createanewnodeandinitiallykeepitsnextpointerpointingtoitself.
• Updatethenextpointerofthenewnodewiththeheadnodeandalsotraversethelisttothetail.Thatmeansinacircularlistweshouldstopatthenodewhosenextnodeishead.