考研C语言顺序表实现以及基本操作【基于指针方式】
1.指针理解, 指针方式和静态数组的区别
2.动态扩容
3.插入、删除、查找元素
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <assert.h>
#define InitSize 5
typedef struct Sequence {
int *data;
int length;
int MaxSize;
} SeqList;
void InitSeq(SeqList &L){
L.data = (int *)malloc(sizeof(int)*InitSize);
L.length = 0;
L.MaxSize = InitSize;
}
bool IncreaseSeq(SeqList &L, int len){
int *p = L.data;
L.data = (int *)malloc(sizeof(int)*(InitSize + len));
if(p==NULL)
return false;
for(int i=0; i<L.MaxSize; i++){
L.data[i] = p[i];
};
free(p);
L.MaxSize += len;
return true;
}
int GetElement(SeqList &L, int i){
if (i < 1 || i > L.MaxSize)
return -1;
return L.data[i-1];
}
bool InsertElement(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 DelElement(SeqList &L, int j){
if(j < 1 || j > L.length)
return false;
for(int i = j; i <= L.length; i++){
L.data[i-1] = L.data[i];
};
L.length--;
return true;
}
bool InitElements(SeqList &L, int len){
if(len < 1 || len > L.MaxSize)
return false;
printf("输入要添加的元素:\n");
for(int i = 0; i<len; i++){
scanf("%d", L.data+i);
L.length++;
};
return true;
}
void PrintfElements(SeqList &L){
if(L.length > 0)
printf("元素打印:\n");
for(int i = 0; i<L.length; i++){
printf("%d\n", L.data[i]);
}
}
int main(){
SeqList L;
InitSeq(L);
IncreaseSeq(L, 5);
printf("扩容之后的最大长度是%d\n", L.MaxSize);
InitElements(L, 4);
PrintfElements(L);
int a = GetElement(L,11);
printf("取得值为: %d", a);
InsertElement(L, 2, 3);
DelElement(L, 1);
PrintfElements(L);
system("pause");
return 0;
}