#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include<stdlib.h>
#define InitSize 10
typedef struct {
int *data;
int length;
int MaxSize;
} SeqList;
bool InitList(SeqList &L) {
L.data=(int *)malloc(InitSize*sizeof(int));
L.length=0;
L.MaxSize=InitSize;
return true;
}
bool CreateList(SeqList &L,int n) {
if(n>L.MaxSize||n<=0)
return false;
printf("\n请输入表中元素值:\n");
for(int i=0; i<n; i++)
scanf("%d", &L.data[i]);
L.length=n;
return true;
}
int Length(SeqList L) {
return L.length;
}
void PrintList(SeqList &L) {
printf("\n顺序表中的元素为:\n");
for(int i=0; i<L.length; i++)
printf("%4d",L.data[i]);
printf("\n\n");
}
bool InsertList(SeqList &L,int i,int e) {
if(i<1||i>L.length+1)
return false;
if(L.length>L.MaxSize)
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 DeleteList(SeqList &L,int i,int &e) {
if(i<1||i>L.length)
return false;
e=L.data[i-1];
for(int j=i; j<L.length; j++ )
L.data[j-1]=L.data[j];
L.length--;
printf("\n删除的元素值为:%d\n",e);
return true;
}
int LocateElem(SeqList L,int e) {
for (int j=0; j<L.length; j++)
if(L.data[j]==e) {
return j+1;
}
return 0;
}
int GetElem(SeqList L,int i) {
return L.data[i-1];
}
void IncreaseSize(SeqList L,int len) {
int *p=L.data;
L.data=(int *)malloc((L.MaxSize+len)*sizeof(int));
for(int j=0; j<L.length+len; j++) {
L.data[j]=p[j];
}
L.MaxSize=L.MaxSize+len;
free(p);
}
void gai(SeqList L,int i,int x)
{
L.data[i-1] = x;
}
int main() {
int n;
int e=-1;
SeqList L;
InitList(L);
printf("\n请输入要存入的数据元素个数:\n");
scanf("%d", &n);
CreateList(L,n) ;
printf("\n顺序表的当前长度为:%d\n",Length(L));
PrintList(L);
InsertList(L,1,1);
printf("\n第一个位置插入元素值1后:\n");
PrintList(L);
DeleteList(L,2,e);
printf("\n删除第二个位置元素值后:\n");
PrintList(L);
printf("\n按位查找第三个元素,返回其值:%d\n",GetElem(L,3));
printf("\n按值查找元素3,返回其位序:%d\n",LocateElem(L,3));
IncreaseSize(L,5);
gai(L,1,10);
return 0;
}