版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
基本数据结构StacksQueuesListsTreesElementaryDataStructures2TheStackADT(§2.1.1)TheStackADTstoresarbitraryobjectsInsertionsanddeletionsfollowthelast-infirst-outschemeThinkofaspring-loadedplatedispenserMainstackoperations:push(object):insertsanelementobjectpop():removesandreturnsthelastinsertedelementAuxiliarystackoperations:objecttop():returnsthelastinsertedelementwithoutremovingitintegersize():returnsthenumberofelementsstoredbooleanisEmpty():indicateswhethernoelementsarestoredElementaryDataStructures3ApplicationsofStacksDirectapplicationsvisitedhistoryinaWebbrowserUndosequenceinatexteditorChainofmethodcallsintheJavaVirtualMachineorC++runtimeenvironmentIndirectapplicationsAuxiliarydatastructureforalgorithmsComponentofotherdatastructuresElementaryDataStructures4Array-basedStack(§2.1.1)AsimplewayofimplementingtheStackADTusesanarrayWeaddelementsfromlefttorightAvariabletkeepstrackoftheindexofthetopelement(sizeist+1)S012t…Algorithm
pop():
if
isEmpty()
then throwEmptyStackException
else
t
t1 return
S[t+1]Algorithm
push(o)
if
t
=S.length1then throwFullStackException
else
t
t+1
S[t]oElementaryDataStructures5GrowableArray-basedStack(§1.5)Inapushoperation,whenthearrayisfull,insteadofthrowinganexception,wecanreplacethearraywithalargeroneHowlargeshouldthenewarraybe?incrementalstrategy:increasethesizebyaconstantcdoublingstrategy:doublethesizeAlgorithm
push(o)
if
t
=S.length1then
A
newarrayof size…
for
i
0to
tdo
A[i]S[i]
SA
t
t+1
S[t]oElementaryDataStructures6ComparisonoftheStrategiesWecomparetheincrementalstrategyandthedoublingstrategybyanalyzingthetotaltimeT(n)neededtoperformaseriesofnpushoperationsWeassumethatwestartwithanemptystackrepresentedbyanarrayofsize1Wecallamortizedtimeofapushoperationtheaveragetimetakenbyapushovertheseriesofoperations,i.e.,T(n)/nElementaryDataStructures7AnalysisoftheIncrementalStrategyWereplacethearrayk=n/ctimesThetotaltimeT(n)ofaseriesofnpushoperationsisproportionalton+c+2c+3c+4c+…+kc=n+c(1+2+3+…+k)=n+ck(k+1)/2Sincecisaconstant,T(n)isO(n+
k2),
i.e.,O(n2)TheamortizedtimeofapushoperationisO(n)ElementaryDataStructures8DirectAnalysisoftheDoublingStrategyWereplacethearrayk=log2
ntimesThetotaltimeT(n)ofaseriesofnpushoperationsisproportionalton+1+2+4+8+…+2k
=n
+2k+1
-1
=2n-1T(n)isO(n)TheamortizedtimeofapushoperationisO(1)geometricseries12148ElementaryDataStructures9TheaccountingmethoddeterminestheamortizedrunningtimewithasystemofcreditsanddebitsWeviewacomputerasacoin-operateddevicerequiring1cyber-dollarforaconstantamountofcomputing.AccountingMethodAnalysisoftheDoublingStrategyWesetupaschemeforchargingoperations.Thisisknownasanamortizationscheme.Theschememustgiveusalwaysenoughmoneytopayfortheactualcostoftheoperation.Thetotalcostoftheseriesofoperationsisnomorethanthetotalamountcharged.(amortizedtime)(total$charged)/(#operations)ElementaryDataStructures10AmortizationSchemefortheDoublingStrategyConsideragainthekphases,whereeachphaseconsistingoftwiceasmanypushesastheonebefore.Attheendofaphasewemusthavesavedenoughtopayforthearray-growingpushofthenextphase.Attheendofphaseiwewanttohavesavedicyber-dollars,topayforthearraygrowthforthebeginningofthenextphase.02456731$$$$$$$$0245678911310121314151$$Wecharge$3forapush.The$2savedforaregularpushare“stored”inthesecondhalfofthearray.Thus,wewillhave2(i/2)=icyber-dollarssavedatthenendofphasei.Therefore,eachpushrunsinO(1)amortizedtime;npushesruninO(n)time.ElementaryDataStructures11TheQueueADT(§2.1.2)TheQueueADTstoresarbitraryobjectsInsertionsanddeletionsfollowthefirst-infirst-outschemeInsertionsareattherearofthequeueandremovalsareatthefrontofthequeueMainqueueoperations:enqueue(object):insertsanelementattheendofthequeueobjectdequeue():removesandreturnstheelementatthefrontofthequeueAuxiliaryqueueoperations:objectfront():returnstheelementatthefrontwithoutremovingitintegersize():returnsthenumberofelementsstoredbooleanisEmpty():indicateswhethernoelementsarestoredExceptionsAttemptingtheexecutionofdequeueorfrontonanemptyqueuethrowsanEmptyQueueExceptionElementaryDataStructures12ApplicationsofQueuesDirectapplicationsWaitinglinesAccesstosharedresources(e.g.,printer)MultiprogrammingIndirectapplicationsAuxiliarydatastructureforalgorithmsComponentofotherdatastructuresElementaryDataStructures13SinglyLinkedListAsinglylinkedlistisaconcretedatastructureconsistingofasequenceofnodesEachnodestoreselementlinktothenextnodenextelemnodeABCDElementaryDataStructures14QueuewithaSinglyLinkedListWecanimplementaqueuewithasinglylinkedlistThefrontelementisstoredatthefirstnodeTherearelementisstoredatthelastnodeThespaceusedisO(n)andeachoperationoftheQueueADTtakesO(1)timefrnodeselementsElementaryDataStructures15ListADT(§2.2.2)TheListADTmodelsasequenceofpositionsstoringarbitraryobjectsItallowsforinsertionandremovalinthe“middle”Querymethods:isFirst(p),isLast(p)Accessormethods:first(),last()before(p),after(p)Updatemethods:replaceElement(p,o),s(p,q)insertBefore(p,o),insertAfter(p,o),insertFirst(o),insertLast(o)remove(p)ElementaryDataStructures16DoublyLinkedListAdoublylinkedlistprovidesanaturalimplementationoftheListADTNodesimplementPositionandstore:elementlinktothepreviousnodelinktothenextnodeSpecialtrailerandheadernodesprevnextelemtrailerheadernodes/positionselementsnodeElementaryDataStructures17Trees(§2.3)Incomputerscience,atreeisanabstractmodelofahierarchicalstructureAtreeconsistsofnodeswithaparent-childrelationApplications:OrganizationchartsProgrammingenvironmentsComputers”R”UsSalesR&DManufacturingLaptopsDesktopsUSInternationalEuropeAsiaCanadaElementaryDataStructures18TreeADT(§2.3.1)WeusepositionstoabstractnodesGenericmethods:integersize()booleanisEmpty()objectIteratorelements()positionIteratorpositions()Accessormethods:positionroot()positionparent(p)positionIteratorchildren(p)Querymethods:booleanisInternal(p)booleanisExternal(p)booleanisRoot(p)Updatemethods:s(p,q)objectreplaceElement(p,o)AdditionalupdatemethodsmaybedefinedbydatastructuresimplementingtheTreeADTElementaryDataStructures19PreorderTraversal(§2.3.2)AtraversalvisitsthenodesofatreeinasystematicmannerInapreordertraversal,anodeisvisitedbeforeitsdescendantsApplication:printastructureddocumentMakeMoneyFast!1.MotivationsReferences2.Methods2.1Stock
Fraud2.2Ponzi
Scheme1.1Greed1.2Avidity2.3Bank
Robbery123546789Algorithm
preOrder(v)visit(v)for
eachchildwofv preorder(w)ElementaryDataStructures20PostorderTraversal(§2.3.2)Inapostordertraversal,anodeisvisitedafteritsdescendantsApplication:computespaceusedbyfilesinadirectoryanditssubdirectoriesAlgorithm
postOrder(v)for
eachchildwofv postOrder(w)visit(v)cs16/homeworks/todo.txt
1Kprograms/DDR.java
10KStocks.java
25Kh1c.doc
3Kh1nc.doc
2KRobot.java
20K931724568ElementaryDataStructures21BinaryTrees(§2.3.3)Abinarytreeisatreewiththefollowingproperties:EachinternalnodehastwochildrenThechildrenofanodeareanorderedpairWecallthechildrenofaninternalnodeleftchildandrightchildAlternativerecursivedefinition:abinarytreeiseitheratreeconsistingofasinglenode,oratreewhoseroothasanorderedpairofchildren,eachofwhichisabinarytreeApplications:arithmeticexpressionsdecisionprocessessearchingABCFGDEHIElementaryDataStructures22ArithmeticExpressionTreeBinarytreeassociatedwithanarithmeticexpressioninternalnodes:operatorsexternalnodes:operandsExample:arithmeticexpressiontreefortheexpression(2(a-1)+(3b))+-2a13bElementaryDataStructures23DecisionTreeBinarytreeassociatedwithadecisionprocessinternalnodes:questionswithyes/noanswerexternalnodes:decisionsExample:diningdecisionWantafastmeal?Howaboutcoffee?Onexpenseaccount?StarbucksIn‘NOutAntoine'sDenny’sYesNoYesNoYesNoElementaryDataStructures24PropertiesofBinaryTreesNotationn numberofnodese numberofexternalnodesi numberofinternalnodesh heightProperties:e=i+
1n=
2e-
1hih(n-
1)/2e
2hh
log2
eh
log2(n+
1)
-
1ElementaryDataStructures25InorderTraversalInaninordertraversalanodeisvisitedafteritsleftsubtreeandbeforeitsrightsubtreeApplication:drawabinarytreex(v)=inorderrankofvy(v)=depthofvAlgorithm
inOrder(v)if
isInternal(v)inOrder(leftChild(v))visit(
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 健康果实:柑橘病虫害防治新策略
- 果农必读:果树病虫害防治手册
- 分股协议书范本合同参考5篇
- 合火合同书样本6篇
- 2024年事业单位招聘考试甘肃省金昌市职业能力倾向测验题库含答案解析
- 2024年事业单位招聘考试安徽省铜陵市职业能力倾向测验题库含答案解析
- 《移动机器人+词汇GT+42830-2023》详细解读
- 2023年化妆品店工作总结
- 2023年化纤厂生产班长年终总结
- 2023年化工生产调度工作总结
- 《制作纸飞机》(教案) 综合实践一年级上册
- 引风机解体检修(厚义书苑)
- 大中型地面光伏电站设计要点(夏)
- 食品添加剂欧盟编码纯英文版
- 教练技术第一阶段导师讲义28页版本
- 【Excel模板】Beta计算器
- 模切检验标准
- 细数活性污泥法数学模型ASM
- ERP服务项目合同(共8页)
- 汽车理论课后作业matlab编程详解(带注释)
- 部编版语文二年级下册期中专项复习:默写 按课文内容填空
评论
0/150
提交评论