structures in c++ introduction to linked lists · structures in c++ introduction to linked lists cs...

31
Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer Science, UCSB

Upload: others

Post on 19-Oct-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

StructuresinC++IntroductiontoLinkedLists

CS16:SolvingProblemswithComputersILecture#14

ZiadMatni

Dept.ofComputerScience,UCSB

Page 2: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

LectureOutlineStructures (Ch.10.1)•  Definingstructures•  Membervariablesandfunctions•  Structuresinfunctions•  Hierarchyinstructures•  Initializingstructures

LinkedLists(Ch.13.1)•  Wewillcovereverythinginthissection

– WearenotcoveringCh.13.2section!

5/24/18 Matni,CS16,Sp18 2

Page 3: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

First…WhatIsaClass?

•  Aclassisadatatypewhosevariablesarecalledobjects

•  Somepre-defineddatatypesyouhaveusedare:int,char,double

•  Somepre-definedclassesyouhaveusedare:ifstream,string,vector

•  Youcanalsodefineyourownclassesaswell

5/24/18 Matni,CS16,Sp18 3

Page 4: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

ClassDefinitions

•  Todefinea“class”,weneedto…– Describethekindsofvaluesthevariablecanhold•  Numbers?Characters?Both?Somethingelse?

– Describethememberfunctions• Whatcanwedowiththesevalues?

•  Wewillstartbydefiningstructuresasafirststeptowarddefiningclasses

5/24/18 Matni,CS16,Sp18 4

Page 5: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

STRUCTURES

5/24/18 Matni,CS16,Sp18 5

Page 6: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

Structures

•  Astructure’susecanbeviewedasanobject

•  Let’ssayitdoesnotcontainanymemberfunctions(fornow…)

•  Itdoescontainmultiplevaluesofpossiblydifferenttypes

•  We’llcallthesemembervariables

5/24/18 Matni,CS16,Sp18 6

Page 7: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

StructuresforData

•  Thesemultiplevaluesarelogicallyrelatedtooneanotherandcometogetherasasingleitem–  Examples:AbankCertificateofDeposit(CD)whichhasthefollowingvalues: abalance aninterestrate aterm(howmanymonthstomaturity)

–  Astudentrecordwhichhasthefollowingvalues: thestudent’sIDnumber thestudent’slastname thestudent’sfirstname thestudent’sGPA5/24/18 Matni,CS16,Sp18 7

Whatkindofvaluesshouldthese

individuallybe?!

Whatkindofvaluesshouldthese

individuallybe?!

Page 8: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

TheCDStructureExample:Definition•  TheCertificateofDepositstructurecanbedefinedas

structCDAccount

{ doublebalance; //adollaramount

doubleinterest_rate; //apercentage intterm; //atermamountinmonths

};

•  Keywordstructbeginsastructuredefinition•  CDAccountisthestructuretag–thisisthestructure’stype•  Membernamesareidentifiersdeclaredinthebraces

5/24/18 Matni,CS16,Sp18 8

Remember this semicolon!

Page 9: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

UsingtheStructure

•  Structuredefinitionshouldbeplacedoutsideanyfunctiondefinition–  Includingoutsideofmain()–  Thismakesthestructuretypeavailabletoallcodethatfollowsthestructuredefinition(i.e.global)

•  TodeclaretwovariablesoftypeCDAccount:CDAccountmy_account,your_account;

my_accountandyour_accountcontaindistinctmembervariablesbalance,interest_rate,andterm

5/24/18 Matni,CS16,Sp18 9

Page 10: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

SpecifyingMemberVariables•  Membervariablesarespecifictothestructurevariableinwhichtheyaredeclared

•  Syntaxtospecifyamembervariable(notethe‘.’) Structure_Variable_Name . Member_Variable_Name

•  Giventhedeclaration: CDAccountmy_account,your_account;

•  Usethedotoperatortospecifyamembervariable,e.g. my_account.balance isadouble my_account.interest_rate isadouble my_account.term isanint

5/24/18 Matni,CS16,Sp18 10

Page 11: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

5/24/18 Matni,CS16,Sp18 11

Notethestructdefinitionisplacedbeforemain()

Page 12: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

5/24/18 Matni,CS16,Sp18 12

NotethedeclarationofCDAccount

Notethecalculationsdone

withthestructure’s

membervariables

Wearegoingto“fillin”thedatastructurethat’s“account”usingafunction…

Page 13: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

5/24/18 Matni,CS16,Sp18 13

Notetheuseofthestructure’smembervariableswithaninputstream.

Notethatthestructureispassedintothefunctionascall-by-reference.

Youcanalsopassa

structurecall-by-value.

Page 14: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

DuplicateNames

•  Membervariablenamesduplicatedbetweenstructuretypesarenotaproblem•  Thisisbecausewehavetousethedotoperator•  super_grow.quantityandapples.quantityaredifferentvariablesstoredin

differentlocationsincomputermemory

5/24/18 Matni,CS16,Sp18 14

structFertilizerStock{doublequantity;doublenitrogen_content;};FertilizerStocksuper_grow;

structCropYield{intquantity;doublesize;};CropYieldapples;

Page 15: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

StructuresasReturnFunctionTypes

•  Structurescanalsobethetypeofavaluereturnedbyafunction

Example: CDAccountshrink_wrap (doublethe_balance,doublethe_rate,intthe_term)

{CDAccounttemp;temp.balance=the_balance;temp.interest_rate=the_rate;temp.term=the_term;returntemp;}

5/24/18 Matni,CS16,Sp18 15

Whatisthisfunctiondoing?

Page 16: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

Example:UsingFunctionshrink_wrap

•  shrink_wrapbuildsacompletestructurevalueinthestructuretemp,whichisreturnedbythefunction

•  Wecanuseshrink_wraptogiveavariableoftypeCDAccountavalueinthisway:CDAccountnew_account;new_account=shrink_wrap(1000.00,5.1,11);

5/24/18 Matni,CS16,Sp18 16

Page 17: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

AssignmentandStructures•  Theassignmentoperator(=)canalsobeusedtogivevaluestostructuretypes•  UsingtheCDAccountstructureagainforexample:

CDAccountmy_account,your_account;my_account.balance=1000.00;my_account.interest_rate=5.1;my_account.term=12;your_account=my_account;

•  Note:Thislastlineassignsallmembervariablesinyour_accountthecorrespondingvaluesinmy_account

5/24/18 Matni,CS16,Sp18 17

Page 18: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

HierarchicalStructures

•  Structurescancontainmembervariablesthatarealsostructures

•  structPersonInfocontainsaDatestructure

5/24/18 Matni,CS16,Sp18 18

structDate{intmonth;intday;intyear;};

structPersonInfo{doubleheight;intweight;Datebirthday;};

Page 19: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

UsingPersonInfoAnexampleon“.”operatoruse

•  AvariableoftypePersonInfoisdeclared:

PersonInfoperson1; •  Todisplaythebirthyearofperson1,

firstaccessthebirthdaymemberofperson1 cout<<person1.birthday…(wait!notcompleteyet!)

•  Butwewanttheyear,sowenowspecifytheyearmemberofthebirthdaymember cout<<person1.birthday.year;

5/24/18 Matni,CS16,Sp18 19

Page 20: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

5/24/18 Matni,CS16,Sp18 20

Page 21: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

InitializingStructures

•  AstructurecanbeinitializedwhendeclaredExample: structDate {

intmonth; intday; intyear; };

•  Canbeinitializedinthisway–watchoutfortheorder!: Datedue_date={4,20,2018}; Date birthday={12,25,2000};

5/24/18 Matni,CS16,Sp18 21

monthdayyear

Page 22: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

ApplicationofStructures

5/24/18 Matni,CS16,Sp18 22

LinkedLists!

Page 23: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

PointersandLinkedLists

•  DefinitionofLinkedLists:Linearcollectionofdataelements,callednodes,eachpointingtothenextnodebymeansofapointer

•  Listelementscaneasilybeinsertedorremovedwithoutreorganizationoftheentirestructure(unlikearrays)

•  Dataitemsinalinkedlistdonothavetobestoredinonelargememoryblock(again,unlikearrays)

5/24/18 Matni,CS16,Sp18 23

Page 24: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

LinkedLists

•  Youcanbuildalistof“nodes”whicharemadeupofvariablesandpointerstocreateachain.

•  Addinganddeletingnodesinthelinkcanbedoneby“re-routing”pointerlinks.

5/24/18 Matni,CS16,Sp18 24

Page 25: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

Nodes

•  Theboxesinthepreviousdrawingrepresentthenodesofalinkedlist– Nodescontainthedataitem(s)andapointerthatcanpointtoanothernodeofthesametype

– Thepointerspointtoanentirenode,notanindividualitemthatmightbeinthenode

•  Thearrowsinthedrawingrepresentpointers

5/24/18 Matni,CS16,Sp18 25

Page 26: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

NodesandPointers–AnIllustratedExample(shownasDisplay13.1inthetextbook)

5/24/18 26

Page 27: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

ImplementingNodes•  NodesareimplementedinC++asstructsorclasses•  Example:Astructuretostoretwodataitemsandapointertoanothernodeofthesametype,alongwithatypedefinitionmightbe: structListNode{ stringitem;intcount;ListNode*link;}; typedefListNode*ListNodePtr;

5/24/18 Matni,CS16,Sp18 27

This circular definition is allowed in C++

Page 28: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

TheheadofaList

•  Theboxlabeledhead,inDisplay13.1,isnotanode,butsimplyapointervariablethatpointstoanode

•  Pointervariableheadisdeclaredas:ListNodePtrhead;

5/24/18 Matni,CS16,Sp18 28

structListNode{

stringitem;intcount;ListNode*link;};typedefListNode*ListNodePtr;ListNodePtrhead;

Page 29: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

CreatingaLinkedList•  Firstcreatethenode(s)

ListNodemyNode1,myNode2; myNode1.item=“Thingamajiggie”; myNode1.count=5; //etc…

•  Thenlinktheheadpointertothe1stnodeinthelist

head=newListNode; *head=myNode1; //i.e.“whatheadlinkstoismyNode1”

•  Thenlinkalltheothernodestoeachother

*(myNode1.link)=myNode2;//etc…

5/24/18 Matni,CS16,Sp18 29

Checkoutdemo:linkedList.cpp

Page 30: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

YOURTO-DOs

q TurninLab8onMondayq DoHW14byTuesday

q VisitTAs‘officehoursifyouneedhelp!q  Prof.willnothaveofficehoursnextMonday(Universityholiday)

q Enjoythelongweekend!J

5/24/18 Matni,CS16,Sp18 30

Page 31: Structures in C++ Introduction to Linked Lists · Structures in C++ Introduction to Linked Lists CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer

5/24/18 Matni,CS16,Sp18 31