#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define InitSize 5 // 默认的最大长度
//#define IncreaseSize 5// 每次改变的步长
typedef struct {
int* data ; //指示动态分配数组的指针
int MaxSize; //顺序表的最大容量
int length; //顺序表的当前长度
}SeqList;
// 初始化
void InitList(SeqList * L_zhizhen)
{// 用malloc函数申请一片连续的存储空间
L_zhizhen->data = (int*)malloc(sizeof(int) * InitSize);
L_zhizhen->length = 0;
L_zhizhen->MaxSize = InitSize;
}
// 扩展空间,增加动态数组的长度
void IncreaseSize(SeqList * L_zhizhen, int len)
{
printf("增加空间\n");
int *p = L_zhizhen->data;
L_zhizhen->data = (int*)malloc(sizeof(int) * (L_zhizhen->MaxSize + len));
for (int i = 0; i < L_zhizhen->length; i++)
{
L_zhizhen->data[i] = p[i]; //将数据复制到新区域
}
L_zhizhen->MaxSize = L_zhizhen->MaxSize + len; //顺序表最大长度增加len
free(p); // 释放原来空间
}
// 根据位序i插入e元素
bool ListInsert(SeqList * L_zhizhen, int i, int e)
{
if (i < 1 || i > L_zhizhen->length + 1)
{
return false;
}
// 如果满了,扩大空间
if (L_zhizhen->length >= L_zhizhen->MaxSize)
{
IncreaseSize(L_zhizhen, 1);
}
// 先从前往后移动再插入
for (int j = L_zhizhen->length; j >= i; j--) {
L_zhizhen->data[j] = L_zhizhen->data[j - 1];
}
L_zhizhen->data[i - 1] = e;
L_zhizhen->length++;
return true;
}
// 根据位序i删除元素,返回删除的元素值e
bool ListDelete(SeqList * L_zhizhen, int i, int * e)
{
if (i < 1 || i > L_zhizhen->length)
{
return false;
}
*e =L_zhizhen->data[i - 1];
// 直接从后往前移删除
for (int j = i; j < L_zhizhen->length; j++) {
L_zhizhen->data[j - 1] = L_zhizhen->data[j];
}
L_zhizhen->length--;
return true;
}
// 按位序i查找元素,返回值
int GetElem(SeqList * L_zhizhen, int i)
{
if (i < 1 || i > L_zhizhen->length)
{
return 0;
}
return L_zhizhen->data[i - 1];
}
// 按值e查找元素,返回位序
int LocateElem(SeqList * L_zhizhen, int e)
{
for (int i = 0; i < L_zhizhen->length; i++)
{
if (L_zhizhen->data[i] == e) {
return i + 1;
}
}
return 0;
}
// 遍历顺序表元素
void PrintList(SeqList * L_zhizhen)
{
for (int i = 0; i < L_zhizhen->length; i++)
{
printf("%d\t", L_zhizhen->data[i]);
}
printf("\n");
}
int main()
{
SeqList L1;
InitList(&L1);
printf("L1.MaxSize=%d\n",L1.MaxSize);
IncreaseSize(&L1, 5);
printf("L1.MaxSize=%d\n",L1.MaxSize);
ListInsert(&L1, 1, 1);
ListInsert(&L1, 2, 3);
ListInsert(&L1, 2, 2);
printf("L1.data[0]=%d\n",L1.data[0]);
printf("L1.data[1]=%d\n",L1.data[1]);
printf("L1.data[2]=%d\n",L1.data[2]);
int e = 0;
ListDelete(&L1, 1, &e);
printf("L1.data[0]=%d\n",L1.data[0]);
printf("L1.data[1]=%d\n",L1.data[1]);
printf("L1.data[1]=%d\n",GetElem(&L1, 1));
printf("L1.data[%d]=3\n",LocateElem(&L1, 3));
PrintList(&L1);
return 0;
}
标签:顺序,实现,printf,动态分配,int,length,zhizhen,L1,data
From: https://blog.csdn.net/T3057519360/article/details/140742323