基本数据结构StacksQueuesListsTrees_第1页
基本数据结构StacksQueuesListsTrees_第2页
基本数据结构StacksQueuesListsTrees_第3页
基本数据结构StacksQueuesListsTrees_第4页
基本数据结构StacksQueuesListsTrees_第5页
已阅读5页,还剩23页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

基本数据结构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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论