C语言实现顺序表(增删)
内容十分简单,不做过多的文字赘述。
#include<stdio.h> #define MAXSIZE 50 #define ElemType char typedef struct{ ElemType data[MAXSIZE]; int length; }sqlist; void Init(sqlist* l){ l->length = 0; } void CreateList(sqlist* l){ } /** * 顺序表的插入 * :平均时间复杂度O(n) * */ int ListInsert(sqlist* list,int i,ElemType e){ if(i<0||i>list->length+1){ printf("error:位置错误!"); return 0; }else if(list->length>=MAXSIZE){ printf("存储空间已满!"); return 0; }else{ for(int j=list->length;j>=i;j--){ list->data[j] = list->data[j-1]; } list->data[i] = e; list->length++; return 1; } return 0; } /** * 顺序表删除 * 平均时间复杂度:O(n) * */ int ListRemove(sqlist* list,int i,ElemType *e){ if(i<0||i>(*list).length){ printf("error: 位置错误"); return 0; }else{ *e = list->data[i]; for(int j=i;j<list->length;j++){ list->data[j] = list->data[j+1]; } return 1; } return 0; } int main(int argc, char const *argv[]) { sqlist sq; Init(&sq); printf("%d\n",sq.length); ListInsert(&sq,0,'a'); printf("%d: %c\n",sq.length,sq.data[0]); ListInsert(&sq,1,'b'); printf("%d: %c\n",sq.length,sq.data[1]); ListInsert(&sq,2,'c'); printf("%d: %c\n",sq.length,sq.data[2]); ListInsert(&sq,3,'d'); printf("%d: %c\n",sq.length,sq.data[3]); ListInsert(&sq,4,'e'); printf("%d: %c\n",sq.length,sq.data[4]); char a; ListRemove(&sq,1,&a); printf("length: %d index:1:%c return:%c",sq.length,sq.data[1],a); return 0; }
运行结果如下图所示: