生活随笔
收集整理的這篇文章主要介紹了
内功重修之数据结构----数组
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
畢業(yè)也有一段時(shí)間了,一直在做PHP開發(fā),最近感覺到內(nèi)功薄弱,所以是重新開始學(xué)習(xí)內(nèi)功的時(shí)候了(參考郝斌數(shù)據(jù)結(jié)構(gòu)視頻教程)
?動(dòng)態(tài)數(shù)組的實(shí)現(xiàn),本文以C語言實(shí)現(xiàn)一個(gè)數(shù)組功能(抽取幾個(gè)基本方法),包括初始化數(shù)組(init),添加數(shù)據(jù)到數(shù)組(append),插入數(shù)據(jù)到指定位置(insert),刪除指定位置數(shù)據(jù)(delete),取得指定位置數(shù)據(jù)(get);
首先定義一個(gè)數(shù)據(jù)類型(使用結(jié)構(gòu)體)Arr:
struct?Arr?{?????int?*?pBase;??????int?len;??????int?cnt;??};? 以下的操作都是針對(duì)該數(shù)據(jù)類型(struct Arr,本文中的數(shù)組都是指該數(shù)據(jù)類型)進(jìn)行
1.初始化數(shù)組init
???????void?init(struct?Arr?*?pArr,int?length){?????pArr->pBase?=?(int?*)malloc(sizeof(int)?*?length);????if(NULL?==?pArr->pBase){???????printf("初始化失敗\n");???????exit(-1);????}???pArr->len?=?length;???pArr->cnt?=?0;???return;?}?? 2.給數(shù)組添加數(shù)據(jù)append
??????bool?append(struct?Arr?*?pArr,int?date){???????????if?(?is_full(pArr)?)?????????return?false;???????????pArr->pBase[pArr->cnt]?=?date;??????pArr->cnt++;?????return?true;?}? 3.從指定位置插入數(shù)據(jù)insert
????????bool?insert(struct?Arr?*?pArr,?int?pos,?int?date)?{?????int?i;?????if?(is_full(pArr))?????????return?false;??????if?(pos<1?||?pos>pArr->cnt+1)???????????return?false;??//將位置大于pos的數(shù)據(jù)往后移位????for?(i=pArr->cnt-1;?i>=pos-1;?--i)?????{?????????pArr->pBase[i+1]?=?pArr->pBase[i];?????}?????pArr->pBase[pos-1]?=?date;?//將date添加到指定位置????pArr->cnt++;?????return?true;?}? 4.刪除指定位置數(shù)據(jù)delete
????????bool?delete_arr(struct?Arr?*?pArr,?int?pos)?{?????int?i;?????if?(?is_empty(pArr)?)?????????return?false;?????if?(pos<1?||?pos>pArr->cnt)?????????return?false;??????for?(i=pos;?i<pArr->cnt;?++i)?????{?????????pArr->pBase[i-1]?=?pArr->pBase[i];?????}?????pArr->cnt--;?????return?true;?}? 5.查找指定位置數(shù)據(jù)get
?????????int?get(struct?Arr?*?pArr,int?pos){????if?(pos?<?1?||?pos>pArr->cnt+1){???????printf("查找的數(shù)據(jù)不存在\n");???????exit(-1);?????}?????return?pArr->pBase[pos-1];?}? 6.判斷數(shù)組是否達(dá)到最大容量和是否為空的is_full和is_empty
bool?is_empty(struct?Arr?*?pArr)?{?????if?(0?==?pArr->cnt)?????????return?true;?????else?????????return?false;????????}??bool?is_full(struct?Arr?*?pArr)?{?????if?(pArr->cnt?==?pArr->len)?????????return?true;?????else?????????return?false;?}? 暫時(shí)只寫這么多了,由于之前也沒有寫過這些東西,甚至都沒有學(xué)過C,有什么錯(cuò)誤的地方還望指正.
轉(zhuǎn)載于:https://blog.51cto.com/hjyang/857929
總結(jié)
以上是生活随笔為你收集整理的内功重修之数据结构----数组的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。