版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
IntroductiontoComputer(CProgramming)LinkList2023/2/19.10DynamicmemoryallocationDynamicmemoryallocationistheprocessofallocatingmemoryatruntime.Memorymanagementfunctionscanbeusedforallocatingandfreeingmemoryduringprogramexecution.2023/2/19.10DynamicmemoryallocationDynamicmemoryallocationistheprocessofallocatingmemoryatruntime.Memorymanagementfunctionscanbeusedforallocatingandfreeingmemoryduringprogramexecution.FunctionTaskmallocAllocatesrequestsizeofbytesandreturnsapointertothefirstbyteoftheallocatedspacecallocAllocatesspaceforanarrayofelements,initializesthemtozeroandthenreturnsapointertothememoryfreeFreespreviouslyallocatedspacereallocModifiesthesizeofpreviouslyallocatedspace2023/2/19.10.1Useofmalloc()Themallocfunctionreservesablockofmemoryofspecifiedsizeandreturnsapointeroftypevoid:void*malloc(size_tsize);void*meanspointerofanytype.size_tisdefinedinstdlib.h,andsizemeansthebytesizeofmemorytobeallocated.2023/2/19.10.1Useofmalloc()Wecanusemalloclikethefollowing:ptr=(cast-type*)malloc(byte-size);ptrisapointerofcast-type;(cast-type*)isusedfortypeconversion,i.e.convertthevoid*topointerofsomespecifictype;byte-sizeshowshowmanybytestobeallocated.Example:str=(char*)malloc(5);.str2023/2/19.10.1Useofmalloc()Wecanusemalloclikethefollowing:ptr=(cast-type*)malloc(byte-size);ptrisapointerofcast-type;(cast-type*)isusedfortypeconversion,i.e.convertthevoid*topointerofsomespecifictype;byte-sizeshowshowmanybytestobeallocated.Example:str=(char*)malloc(5);.strNotethatthestoragespaceallocateddynamicallyhasnonameandthereforeitscontentscanbeaccessedonlythroughapointer.2023/2/19.10.1Useofmalloc()mallocalsocanbeusedtoallocatespaceforcomplexdatatypessuchasstructures.Example:st_var=(structstudent*)malloc(sizeof(structstudent));2023/2/19.10.1Useofmalloc()RememberThemallocallocatesablockofcontiguousbytes.Theallocationcanfailifthespaceisnotsufficienttosatisfytherequest.Ifitfails,itreturnsaNULL.Weshouldcheckwhethertheallocationissuccessfulbeforeusingthememorypointer.2023/2/19.10.2Useofcalloc()callocisnormallyusedforrequestingmemoryspaceatruntimeforstoringderiveddatatypes,suchasstructures.void*calloc(unsignednum,unsignedsize)Allocatescontiguousspacefornumblocks,eachofsizebytes.Ifthereisnotenoughspace,aNULLpointerisreturned.2023/2/19.10.2Useofcalloc()Thesegmentofaprogramallocatesspaceforastructurevariable:typedefstructstudent{ charname[25]; floatage; longintid_num;}STD;STD*st_ptr;intclass_size=30;st_ptr=(STD*)calloc(class_size,sizeof(STD));…2023/2/19.10.3Useoffree()Whenwenolongerneedtousethatblockforstoringotherinformation,wemayreleasethatblockofmemory.Thisisdonebyusingthefree
function:voidfree(void*ptr)Example:free(st_ptr);2023/2/19.10.3Useoffree()Remember:Itisnotthepointerthatisbeingreleasedbutratherwhatitpointsto.Toreleaseanarrayofmemorythatwasallocatedbycallocweneedonlytoreleasethepointeronce.Itisanerrortoattempttoreleaseelementsindividually.2023/2/1舉例:要分配1個char型數(shù)據(jù)單元char*p;p=(char*)malloc(1);if(p!=NULL){ *p=getch(); printf(“%c”,*p);
free(p);}2023/2/1要分配10個int型數(shù)組int*p;intk;p=(int*)malloc(10*sizeof(int));if(p!=NULL){ for(k=0;k<10;k++) p[k]=k+1;}free(p);2023/2/1一維動態(tài)數(shù)組
#include<stdlib.h>main(){ int*p=NULL,n,i; printf("Pleaseenterarraysize:"); scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
if(p==NULL) { printf("Noenoughmemory!\n"); exit(0); } printf("Pleaseenterthescore:"); for(i=0;i<n;i++) { scanf("%d",p+i); }
for(i=0;i<n;i++) { printf(“%d”,*(p+i)); }
free(p);
}2023/2/19.10.4Useofrealloc()Theprocessofchangingthememorysizealreadyallocatediscalledthereallocation
ofmemory.Wecanusethefunctionrealloctorealizereallocation.void*realloc(void*block,size_tsize)Example:
iftheoriginalallocationisdonebythestatement:ptr=malloc(size);Thereallocationofspacemaybedonebythestatement:ptr=realloc(ptr,newsize);2023/2/19.10.4Useofrealloc()Thisfunctionallocatesanewmemoryspaceofsizenewsizetothepointervariableptr.Thenewmemoryblockmayormaynotbeginatthesameplaceastheoldone.Ifthefunctionisunsuccessfulinlocatingadditionalspace,itreturnsaNULLpointerandtheoriginalblockisfreed.2023/2/1#include<stdio.h>#include<stdlib.h>voidmain(){ char*p=(char*)malloc(1000); char*q=(char*)realloc(p,5000); printf("%x\n",p); printf("%x\n",q);}2023/2/1PointersinstructuresPointerscanalsoappearinstructures.Considerthefollowingcode: structinventory{
char*name; intnumber; floatprice; }product[2];Inthestructuretypeinventory,weusecharacterpointernametooperatethenameofoneproduct.2023/2/1LinkedlistsThestructuremaycontainmorethanoneitemwithdifferentdatatypes.Especially,oneoftheitemsmustbeapointerofthetypeofitsown.Example:
structlink_list { floatage;
structlink_list*next; };2023/2/1LinkedlistsThen,wecandefinetwovariablesoftypelink_list:structlink_listnode1,node2;Thisstatementcreatesspacefortwonodeseachcontainingtowemptyfieldsasshown:node1node2node1.agenode1.nextnode2.agenode2.next2023/2/1LinkedlistsSequentially,ifwewritethebelowassignmentstatement:node1.next=&node2;
thenwecanestablisheda“l(fā)ink”betweennode1andnode2asshown:node1node2node1.agenode1.nextnode2.agenode2.next2023/2/1LinkedlistsWemaycontinuethisprocesstocreatealikedlistofanynumberofvalues.Everylistmusthaveanend.ChasspecialpointervaluecalledNULLthatcanbestoredinthenextfieldofthelastnode.NULLnode1node2node1.agenode1.nextnode2.agenode2.next2023/2/1LinkedlistAlinkedlistisdynamicdatastructure.Therearesomeadvantagesoflinkedlistoverarrays:Theprimaryoneisthatlinkedlistscangroworshrinkinsizeduringtheexecutionofaprogram.Anotheristhatalinkedlistdoesnotwastememoryspace.Thethird,andthemoreimportantadvantageisthatthelinkedlistsprovideflexibilityisallowingtheitemstoberearrangedefficiently.2023/2/1LinkedlistThemajorlimitationoflinkedlistsisthattheaccesstoanyarbitraryitemislittlecumbersomeandtimeconsuming.ANULL1249BNULL1356CNULL1475DNULL1021NULLhead1249135614751021headnodeNote:alinkedlistisadiscretestructure,wecanonlyfindsomenodebythenodebeforeit.2023/2/1OperationsonlinkedlistWecantreatalinkedlistasanabstractdatatypeandperformthefollowingbasicoperations:CreatingalistTraversingthelist(includingcountingtheitemsinthelist,printingthelist,lookingupanitemforeditingorprinting)InsertinganitemDeletinganitemConcatenatingtwolists2023/2/1CreatingalinkedlistWeuseapointerheadtocreateandaccessanonymousnodes.typedefstructlinked_list{ intnum; structlinked_list*next;}node;node*head=NULL;2023/2/1CreatingalinkedlistHeadindicatesthebeginningofthelinkedlist.Thefollowingstatementsstorevaluesinthememberfields:p->num=10;p->next=NULL;headnodenumnext10NULLp2023/2/1CreatingalinkedlistThesecondnodecanbeaddedasfollows:p->next=(node*)malloc(sizeof(node));p->next->num=20;p->next->next=NULL;Thepointercanbemovedfromthecurrentnodetothenextnodebyaself-replacementstatementsuchas:p=p->next;pnumnext10numnext20NULLhead2023/2/1Creatingalinkedlistnode*create(void){intn=0,num;node*head=NULL,*p1,*p2;printf("Inputanitem:"); scanf("%d",&num); while(num!=0){n++;p1=(node*)malloc(sizeof(node));p1->num=num; p1->next=NULL;if(n==1) head=p1;else p2->next=p1;p2=p1;printf("Inputanitem:"); scanf("%d",&num); }return(head);}2023/2/1TraversingalinkedlistWecanusealooptotraversealinkedlistonenodebyonenode,ortherecursion.//countingthenumberofitemsinthelistintcount(node*head){ node*p=head; if(!p) return(0); else return(1+count(p->next));}2023/2/1Traversingalinkedlist//printingitemsinthelistvoidprint(node*head){ node*p; p=head; if(head!=NULL){ do{ printf("No.%d\n",p->num); p=p->next; }while(p!=NULL); }else printf("Thelistisempty!\n");}2023/2/1Traversingalinkedlist
//lookingupsomeiteminthelistnode*search(node*head,intnum){node*p=head;if(head!=NULL){ do{ if(p->num==num){ printf("No.%disfound.\n",num); returnp; }else p=p->next; }while(p!=NULL); printf("No.%disnotfound.\n",num);}else printf("Thequeueisempty.\n");returnNULL;}2023/2/1InsertinganitemInsertinganewitem,sayX,intothelisthasthreesituation:Insertionatthefrontofthelist.Insertionattheendofthelist.Insertionbetweentwonodesofthelist.2023/2/1InsertinganitemInsertingatthefrontofthelist:Setthenextfieldofthenewnodetopointtothestartofthelist.Changetheheadpointertopointtothenewnode.headnodenumnext10Xnumnext5NULL2023/2/1InsertinganitemInsertingattheendofthelist:Setthenextfieldofthelastnodetopointtothenewnode.headnodenumnext10Xnumnext5NULLNULL2023/2/1InsertinganitemInsertingbetweentownodesinthelist(supposethetwonodesisn1andn2):SetthenextfieldofXtopointtonoden2.Setthenextfieldofn1topointtoX.n1numnext10Xnumnext5NULLn2numnext3NULL2023/2/1Insertinganelement//insertanitemattheheadofthelistnode*insert(node*head,node*newnode){ node*p0=newnode,*p1=head; if(head==NULL){ head=p0; p0->next=NULL; }else{ p0->next=p1; head=p0; } returnhead;}2023/2/1Insertinganelement//insertaniteminordernode*insertInOrder(node*head,node*newnode){node*p1=head,*p2=head;if(!head){head=newnode;//鏈表為空,head為插入的節(jié)點(diǎn)
}else{//設(shè)鏈表按升序排列
while(p1){ if(p1->num<=newnode->num){ p2=p1;p1=p1->next; }elsebreak; }//該循環(huán)找到新節(jié)點(diǎn)需要插入的位置
newnode->next=p1; p2->next=newnode;}returnhead;}2023/2/1Insertinganelement//insertsortingnode*sort(node*head){ node*newhead=NULL,*p=head,*q; while(
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 食品安全追溯消費(fèi)者信任反饋建立
- 專業(yè)基礎(chǔ)-房地產(chǎn)經(jīng)紀(jì)人《專業(yè)基礎(chǔ)》真題匯編3
- 農(nóng)場半年度工作匯報
- 統(tǒng)編版五年級語文上冊寒假作業(yè)(十三)有答案
- 二零二五版共有產(chǎn)權(quán)房轉(zhuǎn)讓協(xié)議書3篇
- 二零二五年智能大棚土地承包合作協(xié)議范本3篇
- 宿州航空職業(yè)學(xué)院《英語專業(yè)前沿課程》2023-2024學(xué)年第一學(xué)期期末試卷
- 二零二五版公共安全防范承包合同3篇
- 二零二五年食品包裝設(shè)計及委托加工合同
- 蘇教版初一英語試卷單選題100道及答案
- 春季餐飲營銷策劃
- 企業(yè)會計機(jī)構(gòu)的職責(zé)(2篇)
- 《疥瘡的防治及治療》課件
- Unit4 What can you do Part B read and write (說課稿)-2024-2025學(xué)年人教PEP版英語五年級上冊
- 2025年MEMS傳感器行業(yè)深度分析報告
- 《線控底盤技術(shù)》2024年課程標(biāo)準(zhǔn)(含課程思政設(shè)計)
- 學(xué)校對口幫扶計劃
- 倉庫倉儲安全管理培訓(xùn)課件模板
- 風(fēng)力發(fā)電場運(yùn)行維護(hù)手冊
- 河道旅游開發(fā)合同
- 情人合同范例
評論
0/150
提交評論