structures in c++ introduction to linked lists · structures in c++ introduction to linked lists cs...
TRANSCRIPT
StructuresinC++IntroductiontoLinkedLists
CS16:SolvingProblemswithComputersILecture#14
ZiadMatni
Dept.ofComputerScience,UCSB
LectureOutlineStructures (Ch.10.1)• Definingstructures• Membervariablesandfunctions• Structuresinfunctions• Hierarchyinstructures• Initializingstructures
LinkedLists(Ch.13.1)• Wewillcovereverythinginthissection
– WearenotcoveringCh.13.2section!
5/24/18 Matni,CS16,Sp18 2
First…WhatIsaClass?
• Aclassisadatatypewhosevariablesarecalledobjects
• Somepre-defineddatatypesyouhaveusedare:int,char,double
• Somepre-definedclassesyouhaveusedare:ifstream,string,vector
• Youcanalsodefineyourownclassesaswell
5/24/18 Matni,CS16,Sp18 3
ClassDefinitions
• Todefinea“class”,weneedto…– Describethekindsofvaluesthevariablecanhold• Numbers?Characters?Both?Somethingelse?
– Describethememberfunctions• Whatcanwedowiththesevalues?
• Wewillstartbydefiningstructuresasafirststeptowarddefiningclasses
5/24/18 Matni,CS16,Sp18 4
STRUCTURES
5/24/18 Matni,CS16,Sp18 5
Structures
• Astructure’susecanbeviewedasanobject
• Let’ssayitdoesnotcontainanymemberfunctions(fornow…)
• Itdoescontainmultiplevaluesofpossiblydifferenttypes
• We’llcallthesemembervariables
5/24/18 Matni,CS16,Sp18 6
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?!
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!
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
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
5/24/18 Matni,CS16,Sp18 11
Notethestructdefinitionisplacedbeforemain()
5/24/18 Matni,CS16,Sp18 12
NotethedeclarationofCDAccount
Notethecalculationsdone
withthestructure’s
membervariables
Wearegoingto“fillin”thedatastructurethat’s“account”usingafunction…
5/24/18 Matni,CS16,Sp18 13
Notetheuseofthestructure’smembervariableswithaninputstream.
Notethatthestructureispassedintothefunctionascall-by-reference.
Youcanalsopassa
structurecall-by-value.
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;
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?
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
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
HierarchicalStructures
• Structurescancontainmembervariablesthatarealsostructures
• structPersonInfocontainsaDatestructure
5/24/18 Matni,CS16,Sp18 18
structDate{intmonth;intday;intyear;};
structPersonInfo{doubleheight;intweight;Datebirthday;};
UsingPersonInfoAnexampleon“.”operatoruse
• AvariableoftypePersonInfoisdeclared:
PersonInfoperson1; • Todisplaythebirthyearofperson1,
firstaccessthebirthdaymemberofperson1 cout<<person1.birthday…(wait!notcompleteyet!)
• Butwewanttheyear,sowenowspecifytheyearmemberofthebirthdaymember cout<<person1.birthday.year;
5/24/18 Matni,CS16,Sp18 19
5/24/18 Matni,CS16,Sp18 20
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
ApplicationofStructures
5/24/18 Matni,CS16,Sp18 22
LinkedLists!
PointersandLinkedLists
• DefinitionofLinkedLists:Linearcollectionofdataelements,callednodes,eachpointingtothenextnodebymeansofapointer
• Listelementscaneasilybeinsertedorremovedwithoutreorganizationoftheentirestructure(unlikearrays)
• Dataitemsinalinkedlistdonothavetobestoredinonelargememoryblock(again,unlikearrays)
5/24/18 Matni,CS16,Sp18 23
LinkedLists
• Youcanbuildalistof“nodes”whicharemadeupofvariablesandpointerstocreateachain.
• Addinganddeletingnodesinthelinkcanbedoneby“re-routing”pointerlinks.
5/24/18 Matni,CS16,Sp18 24
Nodes
• Theboxesinthepreviousdrawingrepresentthenodesofalinkedlist– Nodescontainthedataitem(s)andapointerthatcanpointtoanothernodeofthesametype
– Thepointerspointtoanentirenode,notanindividualitemthatmightbeinthenode
• Thearrowsinthedrawingrepresentpointers
5/24/18 Matni,CS16,Sp18 25
NodesandPointers–AnIllustratedExample(shownasDisplay13.1inthetextbook)
5/24/18 26
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++
TheheadofaList
• Theboxlabeledhead,inDisplay13.1,isnotanode,butsimplyapointervariablethatpointstoanode
• Pointervariableheadisdeclaredas:ListNodePtrhead;
5/24/18 Matni,CS16,Sp18 28
structListNode{
stringitem;intcount;ListNode*link;};typedefListNode*ListNodePtr;ListNodePtrhead;
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
YOURTO-DOs
q TurninLab8onMondayq DoHW14byTuesday
q VisitTAs‘officehoursifyouneedhelp!q Prof.willnothaveofficehoursnextMonday(Universityholiday)
q Enjoythelongweekend!J
5/24/18 Matni,CS16,Sp18 30
5/24/18 Matni,CS16,Sp18 31