顺序表的动态分配:
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 100
typedef struct{
int *data;//链表的首地址
int SeqMaxSize;//链表结构体的最大的容量
int length;//链表的当前容量
}Seqlist;//链表结构体
int* InitSeqlist(Seqlist &Seq);
bool InsertSeqlist(Seqlist &Seq,int i,int e);
bool DeletData(Seqlist &Seq,int i,int e);
int LookSeqlist(Seqlist &Seq,int e);
int *Increate_space(Seqlist &Seq);
Seqlist Seq;
int main(){
InitSeqlist(Seq);
int DataTemp;
int *NewAddr;
//给动态分配的静态链表输入值
for(int i=0;i<=5;i++){
scanf("%d\n",&DataTemp);
Seq.data[i]=DataTemp;
Seq.length++;
}
//验证 InsertSeqlist函数
InsertSeqlist(Seq,3,250);
printf("\n\n\n");
for(int i=0;i<=Seq.length;i++){
printf("%d\n",Seq.data[i]);
}
printf("\n\n\n");
DeletData(Seq,3,250);
//验证 DeletData函数
for(int i=0;i<=Seq.length;i++){
printf("%d\n",Seq.data[i]);
}
printf("\n\n\n");
//验证 LookSeqlist函数
printf("%d\n",LookSeqlist(Seq,22));
NewAddr=Increate_space(Seq);//此处不验证
return 0;
}
//fun:初始化链表
//brief:@链表
//return:链表的初始位置
int* InitSeqlist(Seqlist &Seq){
Seq.data = (int *)malloc(sizeof(int)*MaxSize);//malloc在stdlib文件中
Seq.SeqMaxSize = MaxSize;
Seq.length = 0;
return Seq.data;
}
//fun:在连表中插入一个数值
//brief:@链表@插入的位置@插入的值
//return :成功与否
bool InsertSeqlist(Seqlist &Seq,int i,int e){
if(i<0||i>Seq.length){
return false;
}
for(int j=Seq.length;j>=i-1;j--){
Seq.data[j+1]=Seq.data[j];
}
Seq.data[i-1]=e;
Seq.length++;
return true;
}
//fun:在静态链表的i位置删除一个e的值
//brief: @链表@删除的位置@删除的值
//return :成功与否
bool DeletData(Seqlist &Seq,int i,int e){
if(i<0||i>Seq.length){
return false;
}
for(int j=i-1;j<=Seq.length;j++){
Seq.data[j]=Seq.data[j+1];
}
Seq.length--;
return true;
}
//fun:遍历动态分配中的链表的特定元素
//brief:@链表@找的值
//return: 找的值的位置
int LookSeqlist(Seqlist &Seq,int e){
if(Seq.length<=0){
return 0;
}
for(int i=0;i<=Seq.length;i++){
if(Seq.data[i]==e)
return i+1;
}
}
//fun:追加相应空间的函数
//brief:@链表
//return: 链表的首地址
int *Increate_space(Seqlist &Seq){
Seq.data = (int *)malloc(sizeof(int)*MaxSize);//sizeof(int)*MaxSize的值可变
Seq.SeqMaxSize = Seq.SeqMaxSize+Seq.SeqMaxSize;//更具自己申请的空间的大小来决定
return Seq.data;
}