数据结构线性表中的顺序表实现
#include<iostream>
#include<malloc.h>
using namespace std;
typedef int ElemType;
#define InitSize 100
#define LISTINCREMENT 10
typedef struct{
ElemType *data;
int length;//线性表的长度
int listsize; //当前分配的存储容量
}SqList;
int InitList(SqList &L){
//初始化线性表
L.data=(ElemType *)malloc(sizeof(ElemType)*InitSize);
L.length=0;
L.listsize=InitSize;
return 0;
}
int CreateSqList(SqList &L){
for(int i=0;i<10;i++){
L.length++;
L.data[i]=i;
}
return 0;
}
bool ListInsert(SqList &L,int i,ElemType e){
//在第i个位置插入元素e
if(i<1||i>L.length+1) return false;
if(L.length>=L.listsize){
ElemType *newbase=(ElemType *)realloc(L.data,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
L.data=newbase;
L.length+=LISTINCREMENT;
}
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,ElemType &e){
// 删除顺序表中第i个元素,并用e返回删除的元素值
if(i<1||i>L.length) return false;
e=L.data[i-1];
for(int j=i-1;j<L.length;j++)
L.data[j]=L.data[j+1];
--L.length;
return e;
}
void VisitList(SqList L){
for(int i=0;i<L.length;i++)
cout<<L.data[i]<<",";
cout<<endl;
}
int main(){
SqList L;
InitList(L);
CreateSqList(L);
cout<<"线性表是"<<endl;
VisitList(L);
ListInsert(L,2,3);
cout<<"插入元素后的线性表为:"<<endl;
VisitList(L);
int e=0 ;
ListDelete(L,2,e);
cout<<"删除的元素值是:"<<endl;
cout<<e<<endl;
cout<<"删除元素后的线性表为:"<<endl;
VisitList(L);
}
总结
在线性表的实现中,对于插入和删除操作,要注意位置,数组是从0开始,而在我们计算中,是从1开始的