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

33
CS 106B, Lecture 16 Linked Lists This document is copyright (C) Stanford Computer Science and Ashley Taylor, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Marty Stepp, Chris Gregg, Keith Schwarz, Julie Zelenski, Jerry Cain, Eric Roberts, Mehran Sahami, Stuart Reges, Cynthia Lee, and others

Upload: others

Post on 17-Jul-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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

Page 2: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

2

Plan for Today • ContinuingdiscussionofArrayStackfromlastweek• Learnaboutanewwaytostoreinformation:thelinkedlist

Page 3: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

3

A Stack Class • RecallfromThursdayourArrayStack• Bystoringthearrayontheheap,thememoryexistedforalltheStackmemberfunctions

• Onelimitation:ourStackonlystoredints– Howcouldweexpandittobeabletostoreeverytype,liketherealStack?

Page 4: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

4

Template class • Templateclass:Aclassthatacceptsatypeparameter(s).

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

Page 5: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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

Page 6: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

6

Flaws with Arrays • Someaddsareverycostly(whenwehavetoresize)

–  Addingjustoneelementrequirescopyingalltheelements•  Imagineifeverythingwerelikethat?

–  Insteadofjustgrabbinganewsheetofpaper,re-copyallnotestoabiggersheetwhenyourunoutofspace

–  Insteadofjustmakinganewbendinaline,makeeveryonemovetoalargerarea

•  Idea:whatifwecouldjustaddtheamountofmemoryweneed?

4 8 15 16 23 42

Page 7: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

7

Vector and arrays •  Insertingintoanarrayinvolvesshiftingalltheelementsover

–  That'sO(N)• Whatifweweretojustbeabletoeasilyinsert?

4 8 15 23 41

16

Page 8: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

8

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

• Elementsarechainedtogetherinasequence• Eachelementisallocatedontheheap–why?

4 8 15 16 23 41

Page 9: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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

Page 10: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

10

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

Page 11: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

11

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

Page 12: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

12

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

Page 13: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

13

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

Page 14: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

14

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

Page 15: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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;

Page 16: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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;

Page 17: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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;

Page 18: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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

Page 19: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

19

Announcements • Assignment4isdueonThursday–pleasefinishitbeforethen• Youwillgetassignment3feedbackonWednesday• Examlogistics

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

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

Page 20: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

20

Linked List iteration •  Idea:traveleachListNodeoneatatime

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

Page 21: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

21

Linked List iteration •  Idea:traveleachListNodeoneatatime

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

Initializeptrtothefirstnodein(frontnodeof)thelist

Page 22: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

22

Linked List iteration •  Idea:traveleachListNodeoneatatime

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

Moveptrtopointtothenextnodeofthelist

Page 23: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

23

Linked List iteration •  Idea:traveleachListNodeoneatatime

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

Continuedoingthisuntilwehittheendofthelist

Page 24: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

24

Practice Iteratively! • WriteafunctionthattakesinthepointertothefrontofaLinkedListandprintsoutalltheelementsofaLinkedList

voidprintList(ListNode*front){}

Page 25: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

25

Practice Iteratively! • WriteafunctionthattakesinthepointertothefrontofaLinkedListandprintsoutalltheelementsofaLinkedList

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

Page 26: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

26

Iterative Trace • WriteafunctionthattakesinthepointertothefrontofaLinkedListandprintsoutalltheelementsofaLinkedList

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

Page 27: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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;}

Page 28: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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;}

Page 29: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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;}

Page 30: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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;}

Page 31: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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;}

Page 32: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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;}

Page 33: CS 106B, Lecture 16 Linked Lists - Stanford University€¦ · Linked List • Main idea: let's store every element in its own block of memory • Then we can just add one block of

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;}