#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<cmath>
#include<string>
#include<map>
#include<queue>
using namespace std;
typedef long long elemtype;
typedef long long ll;
#define LIST_INIT_LENGTH 100
#define LIST_INCREASE 10
//线性表动态分配存储结构
typedef struct {
elemtype *elem;//存储线性表的基址
ll len;//当前线性表内的长度
ll listsize;//线性表的容量
}sqlist;
//-----------创建(初始化)线性表
ll list_init(sqlist &L){
L.elem=(elemtype *)malloc(LIST_INIT_LENGTH*sizeof(elemtype));//申请空间
if(L.elem==NULL)return 0;//创建失败
L.len=0;
L.listsize=LIST_INIT_LENGTH;
return 1;//代表创建成功
}
//-----线性表的插入操作
ll list_insert(sqlist &L,ll i,elemtype e){
//在线性表L的第i个位置插入数值e;
elemtype *p,*newbase,*q;
if(i<1||i>L.len+1)return 0;//i值不合法
if(L.len>=L.listsize){//线性表已经满了,需要增加空间
//在L.elem的基础上增加空间,注意realloc函数的用法
newbase=(elemtype *)realloc(L.elem,(L.listsize+LIST_INCREASE)*sizeof(elemtype));
if(newbase==NULL)return 0;//申请失败
L.elem=newbase;//新基址
L.listsize+=LIST_INCREASE;//增加储存容量
}
p=L.elem+i-1;//找到待插入的位置
for(q=L.elem+L.len-1;q>=p;q--){
*(q+1)=*q;//插入位置及之后的元素右移
}
*p=e;//插入
++L.len;//当前线性表的长度增加
return 1;//插入成功
}
//---------线性表的删除操作
ll list_delete(sqlist &L,ll i){
elemtype *p,*q;
if(i<1||i>L.len)return 0;//i值不合法
p=&(L.elem[i-1]);//待删除位置
q=&(L.elem[L.len-1]);
for(++p;p<=q;p++){
*(p-1)=*p;//待删除位置及之后的元素左移
}
L.len--;//线性表长度减一
return 1;//删除成功
}
//---------求线性表的长度
ll list_getlength(sqlist L){
return L.len;
}
//----------线性表的销毁
ll list_destroy(sqlist &L){
free(L.elem);//释放线性表的内存空间
//初始化线性表的三个参数
L.len=0;
L.elem=NULL;
L.listsize=0;
return 1;
}
int main(){
sqlist L;
list_init(L);
for(ll i=0;i<=10;i++){
list_insert(L,i+1,i);
}
cout<<"此时线性表的元素为:";
for(ll i=0;i<L.len;i++){
cout<<L.elem[i]<<" ";
}
cout<<endl<<"线性表的长度:"<<list_getlength(L)<<endl;
ll k,e;
cout<<"要插入的数值:";
cin>>e;
cout<<"要插入的位置:";
cin>>k;
if(!list_insert(L,k,e))
cout<<"插入失败"<<endl;
else{
cout<<"此时线性表的元素为:";
for(ll i=0;i<L.len;i++){
cout<<L.elem[i]<<" ";
}
cout<<endl<<"线性表的长度:"<<list_getlength(L)<<endl;
}
cout<<"要删除的位置:";
cin>>k;
if(!list_delete(L,k))
cout<<"删除失败"<<endl;
else{
cout<<"此时线性表的元素为:";
for(ll i=0;i<L.len;i++){
cout<<L.elem[i]<<" ";
}
cout<<endl<<"线性表的长度:"<<list_getlength(L)<<endl;
}
if(list_destroy(L)){
cout<<"销毁线性表成功"<<endl;
}
return 0;
}