靜態表之整型陣列的插入 刪除 查詢

2022-03-27 08:10:52 字數 2355 閱讀 4342

#返回上一級

@author: 張海拔

@update: 2014-01-23

@link: 

1/*2

*author: zhanghaiba

3*date: 2014-1-23

4*file: array.c5*

6*a demo shows array data structure7*/

89 #include 10 #include 11

#define len 1024

12#define cmd_len 128

1314

//public

15void set_array(int a, int

n);16

bool array_insert(int a, int *n, int pos, int

item);

17bool array_delete(int a, int *n, int

pos);

18int array_search(int a, int n, int

item);

19void print_array(int a, int

n);20

2122

int main(void)23

63 }//

while

64return0;

65}6667

68void set_array(int *a, int

n)69

7576

bool array_insert(int *a, int *n, int pos, int

item)

7787

88bool array_delete(int *a, int *n, int

pos)

8998

99int array_search(int *a, int n, int

item)

100108

109110

void print_array(int *a, int

n)111

測試示範

6312

543534

1256

636p

312543

53412

56636

i -1

55insert failed! --check posi 0

55inserted successfully!p

55312

543534

1256

636i 766

inserted successfully!p

55312

543534

1256

63666i 9

77insert failed! --check pos

d -1

insert failed! --check posd 8

insert failed! --check posd 7

delete successfully!p

55312

543534

1256

636d

0delete successfully!p

312543

53412

56636

s 33

not found!s

12found item

12s

312found item

312s

636found item

636p

312543

53412

56636

q陣列在c裡面是原生的資料結構。所以不需要create,而且是乙個賦值方法函式array_set()。

陣列的插入、刪除會使陣列的長度(有效資料長度)變換。可通過返回新長度實現,考慮到還要兼顧引數檢查,所以介面要求傳入長度引數n的指標。

這樣就可以在插入(或刪除)成功的時候修改陣列的長度。

另外,函式宣告部分,int a形式是int *a形式的語法糖(類似地,宣告中,int a[8] 等價於 int(*a)[8])

之所以不寫成int *a,是為了提示使用者該引數接受乙個陣列。int *a則不那麼明顯。

一般來說,我更習慣用int *a,上述實現中,在函式定義(實現)時,我也繼續使用int *a。

值得一提的是,a[2]是*(a+2)的語法糖。使用現代編譯器,陣列下標並不比使用指標的慢。

語法糖好吃,寫**好看,讀**方便,更利於初學者。指標的寫法在老一輩c程式設計師中使用廣泛,也必須掌握。

所以在熟悉了指標用法後,以後都使用陣列下標,這會使程式可讀性更強。

#返回上一級

順序表的查詢 刪除 插入

遇到的問題 malloc realloc的用法 realloc 型別 realloc 原來的記憶體位址,新的大小 型別 指標的問題 要深刻理解指標,指標也是乙個變數,在函式傳遞引數的過程中,作為引數來講,傳遞的也是值。這個值就是指標本身的內容,即指標指向的位址。而 不是傳的指標。所以指標作為函式形參...

靜態鍊錶的插入和刪除

靜態鍊錶相當於是用乙個陣列來實現線性表的鏈式儲存結構,在靜態鍊錶中操作的是陣列。結構體陣列 一 靜態鍊錶的插入操作 靜態鍊錶的插入操作包含兩部分,首先是獲得空閒量的下標,程式 如下 int getcur staticlinklist tan 要想更好的理解,最好結合乙個靜態列表的例項來掌握,下面給出...

java 陣列實現雜湊表的構建,查詢,插入,刪除

以下 以陣列儲存方式實現了雜湊表的建立,查詢,插入,刪除等操作,雜湊函式採用除留餘數法,使用開放定址法中的線性探查法處理衝突 public class hashsearch public intcollision int d,int hashsize public inthashfunc int k...