線性表的順序實現

2022-09-12 00:51:36 字數 2591 閱讀 8886

**:

#include

#include

#define maxsize 50

typedef char elemtype;

typedef struct

elemtype elem[maxsize];

int length;

} sqlist;/*順序表型別定義*/

void initlist(sqlist *&l)/*初始化順序表l*/

l=(sqlist *)malloc(sizeof(sqlist));

l->length =0;

void destroylist(sqlist *l)/*釋放順序表l*/

free(l);

int listempty(sqlist *l)/*判斷順序表l是否為空表*/

return(l->length ==0);

int listlength(sqlist *l)/*返回順序表l的元素個數*/

return(l->length );

void displist(sqlist *l)/*輸出順序表l*/

int i;

if(listempty(l))return;

for(i=0;ilength ;i++)

printf("%c",l->elem[i]);

printf("\n");

int getelem(sqlist *l,int i,elemtype &e)/*獲取順序表l中的第i個元素*/

if(i<1 || i>l->length )

return 0;

e=l->elem [i-1];

return 1;

int locateelem(sqlist *l,elemtype e)/*在順序表l中查詢元素e*/

int i=0;

while (ilength  && l->elem [i]!=e) i++;

if(i>=l->length )

return 0;

else

return i+1;

int listinsert(sqlist *l,int i,elemtype e)/*在順序表l中第i個位置上插入元素e*/

int j;

if(i<1 || i>l->length+1)

return 0;

i--;                           /*將順序表位序轉化為elem下標*/

for (j=l->length;j>i;j--)      /*將elem[i]及後面元素後移乙個位置*/

l->elem[j]=l->elem [j-1];

l->elem [i]=e;

l->length ++;                 /*順序表長度增1*/

return 1;

int listdelete(sqlist *l,int i,elemtype &e) /*順序表l中刪除第i個元素*/

int j;

if(i<1 || i>l->length)

return 0;

i--;       /*將順序表位序轉化為elem下標*/

e=l->elem [i];

for(j=i+1;jlength;j++)  /*將elem[i]以後的元素前移乙個位置*/

l->elem[j-1]=l->elem [j];

l->length --;                 /*順序表長度減1*/

return 1;

void main()

sqlist *l;

elemtype e;

printf("(1)初始化順序表l\n");

initlist(l);

printf("(2)依次採用尾插入法插入a,b,c,d,e元素\n");

listinsert(l,1,'a');

listinsert(l,2,'b');

listinsert(l,3,'c');

listinsert(l,4,'d');

listinsert(l,5,'e');

printf("(3)輸出順序表l:");

displist(l);

printf("(4)順序表l長度=%d\n",listlength(l));

printf("(5)順序表l%s\n",(listempty(l)?"空":"非空"));

getelem(l,3,e);

printf("(6)順序表l的第3個元素=%c\n",e);

printf("(7)元素a的位置=%d\n",locateelem(l,'a'));

printf("(8)在第4個元素位置上插入f元素\n");

listinsert(l,4,'f');

printf("(9)輸出順序表l:");

displist(l);

printf("(10)刪除l的第3個元素\n");

listdelete(l,3,e);

printf("(11)輸出順序表l:");

displist(l);

printf("(12)釋放順序表l\n");

destroylist(l);

線性表順序實現

線性表實現,建立表,插入元素,刪除元素,銷毀表,表的遍歷,表的並集交集差集。不斷更新中。include include include include define list init size 100 初始大小 define error 0 define listincrement 10 增量大小...

線性表的順序實現

include using namespace std 線性表的順序儲存結構 const int maxlistsize 100 class list 構造乙個空線性表 void clear bool isempty 判斷是否為空,若為空,返回true,否則返回false intgetelem in...

線性表的順序實現

線性表的順序表示和實現 include stdio.h define true 1 define false 0 define list init size 30 define list increment 10typedef intelemtype typedef struct sqlist 初始...