cs 106b, lecture 16 linked lists - stanford university€¦ · linked list • main idea:...

Post on 17-Jul-2020

5 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers.

CS106B,Lecture16LinkedLists

Thisdocumentiscopyright(C)StanfordComputerScienceandAshleyTaylor,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyMartyStepp,ChrisGregg,KeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers

2

Plan for Today • ContinuingdiscussionofArrayStackfromlastweek• Learnaboutanewwaytostoreinformation:thelinkedlist

3

A Stack Class • RecallfromThursdayourArrayStack• Bystoringthearrayontheheap,thememoryexistedforalltheStackmemberfunctions

• Onelimitation:ourStackonlystoredints– Howcouldweexpandittobeabletostoreeverytype,liketherealStack?

4

Template class • Templateclass:Aclassthatacceptsatypeparameter(s).

–  Intheheaderandcppfiles,markeachclass/functionastemplated.–  ReplaceoccurrencesoftheprevioustypeintwithTinthecode.–  SeeGeneralStackintoday'sstartercodeforexample//ClassName.htemplate<typenameT>classClassName{...};//ClassName.cpptemplate<typenameT>typeClassName<T>::name(parameters){...}

5

Template .h and .cpp

• BecauseofanoddquirkwithC++templates,theseparationbetween.hheaderand.cppimplementationmustbereduced.–  Eitherwriteallthebodiesinthe.hfile(suggested),//ClassName.h#ifndef_classname_h#define_classname_h

template<typenameT>classClassName{...};template<typenameT>typeClassName<T>::method1(...){...}...

#endif//_classname_h

6

Flaws with Arrays • Someaddsareverycostly(whenwehavetoresize)

–  Addingjustoneelementrequirescopyingalltheelements•  Imagineifeverythingwerelikethat?

–  Insteadofjustgrabbinganewsheetofpaper,re-copyallnotestoabiggersheetwhenyourunoutofspace

–  Insteadofjustmakinganewbendinaline,makeeveryonemovetoalargerarea

•  Idea:whatifwecouldjustaddtheamountofmemoryweneed?

4 8 15 16 23 42

7

Vector and arrays •  Insertingintoanarrayinvolvesshiftingalltheelementsover

–  That'sO(N)• Whatifweweretojustbeabletoeasilyinsert?

4 8 15 23 41

16

8

Linked List • Mainidea:let'sstoreeveryelementinitsownblockofmemory• Thenwecanjustaddoneblockofmemory!• Thenwecanefficientlyinsertintothemiddle(orfront)!• ALinkedListisgoodforstoringelementsinanorder(similartoVector)

• Elementsarechainedtogetherinasequence• Eachelementisallocatedontheheap–why?

4 8 15 16 23 41

9

Parts of a Linked List • WhatdoeseachpartofaLinkedListneedtostore?

–  element–  pointertothenextelement– We'llsaythelastnodepointstonullptr

• TheListNodestruct:structListNode{intdata;//assumeallelementsareintsListNode*next;//constructorListNode(intdata,ListNode*next):data(data),next(next){}//constructorw/outparamsListNode():data(0),next(nullptr){}};

4 8 15 16 23 41

10

Creating a Linked List ListNode*front=newListNode();

11

Creating a Linked List ListNode*front=newListNode();front->data=42;

12

Creating a Linked List ListNode*front=newListNode();front->data=42;front->next=newListNode();

13

Creating a Linked List ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;

14

Creating a Linked List ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;front->next->next=newListNode();

15

Creating a Linked List ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;front->next->next=newListNode();front->next->next->data=17;front->next->next->next=nullptr;

16

Creating a Linked List ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;front->next->next=newListNode();front->next->next->data=17;front->next->next->next=nullptr;

17

No constructor? ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;front->next->next=newListNode();front->next->next->data=17;front->next->next->next=newListNode;

18

No constructor? ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;front->next->next=newListNode();front->next->next->data=17;front->next->next->next=newListNode;front->next->next->next->next=newListNode;//KABOOM

19

Announcements • Assignment4isdueonThursday–pleasefinishitbeforethen• Youwillgetassignment3feedbackonWednesday• Examlogistics

– MidtermreviewsessiononTuesday(tomorrow!),from7:00-8:30PM,inGatesB01,ledbySLPeter

– MidtermisonWednesday,July25,from7:00-9:00PMinHewlett200–  Completeassignment4beforethemidterm–backtrackingwillbetested

20

Linked List iteration •  Idea:traveleachListNodeoneatatime

– Noeasywayto"indexin"likewithVector.Why?• Generalsyntax:for(ListNode*ptr=list;ptr!=nullptr;ptr=ptr->next){/*…useptr…*/}

21

Linked List iteration •  Idea:traveleachListNodeoneatatime

– Noeasywayto"indexin"likewithVector.Why?• Generalsyntax:for(ListNode*ptr=list;ptr!=nullptr;ptr=ptr->next){/*…useptr…*/}

Initializeptrtothefirstnodein(frontnodeof)thelist

22

Linked List iteration •  Idea:traveleachListNodeoneatatime

– Noeasywayto"indexin"likewithVector.Why?• Generalsyntax:for(ListNode*ptr=list;ptr!=nullptr;ptr=ptr->next){/*…useptr…*/}

Moveptrtopointtothenextnodeofthelist

23

Linked List iteration •  Idea:traveleachListNodeoneatatime

– Noeasywayto"indexin"likewithVector.Why?• Generalsyntax:for(ListNode*ptr=list;ptr!=nullptr;ptr=ptr->next){/*…useptr…*/}

Continuedoingthisuntilwehittheendofthelist

24

Practice Iteratively! • WriteafunctionthattakesinthepointertothefrontofaLinkedListandprintsoutalltheelementsofaLinkedList

voidprintList(ListNode*front){}

25

Practice Iteratively! • WriteafunctionthattakesinthepointertothefrontofaLinkedListandprintsoutalltheelementsofaLinkedList

voidprintList(ListNode*front){for(ListNode*ptr=front;ptr!=nullptr;ptr=ptr->next){cout<<ptr->data<<endl;}}

26

Iterative Trace • WriteafunctionthattakesinthepointertothefrontofaLinkedListandprintsoutalltheelementsofaLinkedList

voidprintList(ListNode*front){for(ListNode*ptr=front;ptr!=nullptr;ptr=ptr->next){cout<<ptr->data<<endl;}}

27

Alternative Iteration for(ListNode*ptr=front;ptr!=nullptr;ptr=ptr->next){//dosomethingwithptr}

isequivalentto:ListNode*ptr=front;while(ptr!=nullptr){//orwhile(ptr)//dosomethingwithptrptr=ptr->next;}

28

A Temporary Solution What'swrong?intmain(){ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;front->next->next=nullptr;

while(front!=nullptr){cout<<front->data<<"";front=front->next;}//continueusingfrontreturn0;}

29

A Temporary Solution What'swrong?intmain(){ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;front->next->next=nullptr;

while(front!=nullptr){cout<<front->data<<"";front=front->next;}//continueusingfrontreturn0;}

30

A Temporary Solution What'swrong?intmain(){ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;front->next->next=nullptr;

while(front!=nullptr){cout<<front->data<<"";front=front->next;}//continueusingfrontreturn0;}

31

A Temporary Solution What'swrong?intmain(){ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;front->next->next=nullptr;

while(front!=nullptr){cout<<front->data<<"";front=front->next;}//continueusingfrontreturn0;}

32

A Temporary Solution What'swrong?intmain(){ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;front->next->next=nullptr;

while(front!=nullptr){cout<<front->data<<"";front=front->next;}//orphanedmemoryandemptylist!return0;}

33

Correct Version intmain(){ListNode*front=newListNode();front->data=42;front->next=newListNode();front->next->data=-3;front->next->next=nullptr;ListNode*ptr=front;

while(ptr!=nullptr){cout<<ptr->data<<"";ptr=ptr->next;}//frontstillhaspointertolistreturn0;}

top related