线性表代码实现

线性表理解不难,理清删除元素和插入元素的的前驱和后继的关系就可以了。删除就是要先将需要删除的位置空出来然后从需要删除的位置开始把后面的元素往前搬。插入就是将插入的地方空出来从最末尾开始将元素往后搬。

下面是C语言的代码实现。

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
}SqList;

int InitList(SqList &L){
L.elem = (ElemType *)malloc(MAX_SIZE * (sizeof(ElemType)));
L.length = 0;
printf("init success \n");
return 0;
}

int InsertList(SqList &L,int i,ElemType e){
if (i<1 || i>L.length+1) return 0;
for (int j=L.length-1;j>=i-1;j--){
L.elem[j+1] = L.elem[j];
}
L.elem[i-1] = e;
L.length ++;
return 0;
}

int DeleteElem(SqList &L,int i){
if (i<1 || i>L.length+1) return 0;
for(int j=i-1;j<=L.length-1;j++){
L.elem[j] = L.elem[j+1];
}
L.length --;
return 0;
}

int FindELem(SqList &L,ElemType e){
for (int i=0;i<=L.length-1;i++){
if(e == L.elem[i]){
printf("find elem in list\n");
return 0;
}
}
printf("elem not in list\n");
return 0;
}

int main(){
SqList L;
InitList(L);
for (int i=0;i<=10;i++){
InsertList(L,i+1,i);
}
InsertList(L,5,55);
DeleteElem(L,5);
DeleteElem(L,8);
FindELem(L,10);
for (int i=1;i<=10;i++){
printf("%d\n",L.elem[i-1]);
}
}

 

posted @ 2022-03-23 12:00  Ccdjun  阅读(121)  评论(0编辑  收藏  举报