線性表之順序表C 實現

2022-02-04 10:06:09 字數 3501 閱讀 8539

線性表之順序表

一、標頭檔案:seqlist.h

1

//順序線性表的標頭檔案

2 #include3

4const

int maxsize = 100;5

//定義順序表seqlist的模板類

6 template

7class

seqlist

11//

順序表有參構造器(建立乙個長度為n的順序表)

12   seqlist(datatype array, int

n);13

//順序表析構函式

14   ~seqlist(){}

15//

求順序表的長度

16int getlength()

17//

順序表按位查詢,返回i位置的元素

18   datatype getelement(int

i);19

//順序表按值查詢,返回該元素所在的位置

20int

getlocal(datatype x);

21//

順序表在指定的位置插入指定的元素

22void insert(int

i, datatype x);

23//

順序表刪除元素,返回刪除的元素

24   datatype delete(int

i);25

//輸出順序表中的元素

26void

printseqlist();

27private:28

//一維陣列,存放資料元素

29datatype data[maxsize];

30//

順序表的長度

31int

length;

32};

3334

//實現順序表有參構造器

35 template

36 seqlist::seqlist(datatype array, int

n)37

42//

給順序表的儲存元素的陣列賦值

43for (int i = 0; i < n; i++)

4447

//給順序表的長度賦值

48   length =n;49}

5051

//實現順序表按位查詢

52 template

53 datatype seqlist::getelement(int

i)54

60else

6165}66

67//

實現順序表按值查詢,返回該元素所在的位置

68 template

69int seqlist::getlocal(datatype x)

7080}81

//如果指定的元素不在順序表中,則返回位置為0

82return0;

83}8485

//實現順序表插入元素

86 template

87void seqlist::insert(int

index, datatype x)

8894

if (index<1 || index>length + 1)95

98//

如何插入的位置合理,則把順序表中從最後位置到指定插位置的元素整體向後移動乙個位置

99for (int j = length; j >= index; j--)

100103

//給插入的位置放入指定的元素

104   data[index - 1] =x;

105   length++;

106}

107108

//實現順序表刪除指定位置的元素

109 template

110 datatype seqlist::delete(int

index)

111119

else

120128

//刪除順序表中的元素後,其長度減1

129     length--;

130}

131return

x;132

}133

134//

順序輸出順序表中的元素

135 template

136void seqlist::printseqlist()

137142

else

143149     cout <

150}

151 }

二、測試線性表之順序表:testseqlist.cpp

1 #include2 #include"

seqlist.h"3

using

namespace

std;

4void

show()58

intmain()9;

11   seqlist seqlist = seqlist(array,10

);12   cout << "

順序表為:

"<

13seqlist.printseqlist();

14show();

15   cout << "

順序表的長度為:

"<< seqlist.getlength()<

16   cout << "

第三個位置的元素是:

"<< seqlist.getelement(3) <

17   cout << "

元素3的位置是:

"<< seqlist.getlocal(3) <

18show();

19   cout << "

在第5個位置插入元素22

"<

20   seqlist.insert(5, 22

);21   cout << "

順序表為:

"<

22seqlist.printseqlist();

23   cout << "

順序表的長度為:

"<< seqlist.getlength() <

24show();

25   cout << "

刪除第5個位置的元素

"<

26   seqlist.delete(5

);27   cout << "

順序表為:

"<

28seqlist.printseqlist();

29   cout << "

順序表的長度為:

"<< seqlist.getlength() <

30show();

31return0;

32 }

三、執行示例結果

C 實現順序表(線性表)

基本思想是使用陣列作為盛放元素的容器,陣列一開始的大小要實現確定,並使用乙個pointer指向順序表中最後的元素。順序表中的元素是陣列中元素的子集。順序表在記憶體中是連續的,優勢是查詢,弱勢是插入元素和刪除元素。為避免裝箱拆箱,這裡使用泛型,代替object。使用object的例子可以參照這個鏈結中...

c語言線性表之順序表實現

避免重複編譯 ifndef seqlist h define seqlist h include include include define seqlist init size 8 define inc size 3 typedef int elmetype typedef struct seql...

線性表之順序表

資料結構草草學過,不過沒有認真運用過。雖然知道一些最為基本的抽象型別及一些常用操作,不過叫我把這些基本的演算法寫出來我也 是寫不出來的。因為常說資料結構 演算法是乙個程式設計師最基本的素質,所以這次認真加以複習。在複習的同時我盡量將自己學習的其他的 一些基本知識比如c 中的物件導向思想也引入進來,同...