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