C语言数据结构顺序表基本操作实现



//
顺序表基本操作 #include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> using namespace std; const int InitSize=50; typedef struct { int *data; int listsize,length;//可变长的顺序表存储结构 }SqList; SqList create_list() { SqList* l=(SqList*)malloc(sizeof(SqList)); return *l; } int init_list(SqList *L) { L->data=(int*)malloc(sizeof(int)*InitSize); if(!(L->data)) return 0; L->length=0; L->listsize=InitSize; return 1; } void output_all(SqList L) { for(int i=0;i<L.length;i++) cout<<L.data[i]<<' '; cout<<endl; } bool ListInsert(SqList *L,int i,int e) { //在第i个位置插入元素e if(i<1||i>L->length+1) return false; if(L->length>=L->listsize) return false; for(int j=L->length;j>=i;j--) { L->data[j]=L->data[j-1]; } L->data[i-1]=e; L->length++; return true; } bool ListDelete(SqList *L,int i, int * val) { //在第i个位置删除元素 if(L->length==0) return false; if(i<1||i>L->length+1) return false; *val=L->data[i-1]; for(int j=i;j<L->length;j++) { L->data[j-1]=L->data[j]; } L->length--; return true; } int LocateElem(SqList L,int e) { //查找顺序表中第一个等于e的值的序列 for(int i=0;i<L.length;i++) { if(L.data[i]==e) return i+1; } return 0; } int main() { SqList L=create_list(); if(init_list(&L)) cout<<"分配成功"<<endl; else cout<<"分配失败"<<endl; int a=1; cout<<"开始为顺序表赋值,键入0结束赋值"<<endl; while(a) { cin>>a; if(a==0) break; L.data[L.length]=a; L.length++; } cout<<"赋值结束,当前顺序表长度为"<<L.length<<endl; int index,val; cout<<"执行顺序表插入操作,给出插入位置index以及插入的值val"<<endl; cin>>index>>val; ListInsert(&L,index,val); output_all(L); cout<<"插入结束,当前顺序表长度为"<<L.length<<endl; cout<<"执行顺序表删除操作,给出删除位置index"<<endl; cin>>index; int del_num; ListDelete(&L,index,&del_num); cout<<"删除结束,当前顺序表长度为"<<L.length<<' '<<"删除的值为"<<del_num<<endl; output_all(L); cout<<"执行顺序表查询操作,给出想要查询的元素的值"<<endl; int search_val; cin>>search_val; cout<<search_val<<"第一个出现的位置在"<<LocateElem(L,search_val)<<endl; }

 

posted @ 2021-04-09 14:35  weihy  阅读(344)  评论(0编辑  收藏  举报