#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int DataType;
typedef struct SeqList
{
DataType* data;
int size;//当前大小
int capacity;//最大容量
}SL;
void init(SL* pl);//初始化
void clear(SL* pl);//清空
void destroy(SL* pl);//销毁
void print(SL* pl);//打印
void check(SL* pl);//检查是否溢出
void addLast(SL* pl, DataType x);//添加
void add(SL* pl, int idx, DataType x);//索引添加
DataType removeLast(SL* pl);//删除
DataType remove(SL* pl, int idx);//索引删除
DataType getLast(SL* pl);//查询数据
DataType get(SL* pl, int idx);//查询数据
int find(SL* pl, DataType x);//查询索引
void set(SL* pl, int idx, DataType x);//修改
int isEmpty(SL* pl);//判空
int size(SL* pl);//获取大小
#include "SeqList.h"
void init(SL* pl)
{
assert(pl);
pl->data = (DataType*)malloc(sizeof(DataType) * 4);//初始化4个大小空间
//初始化失败
if (pl->data == NULL)
{
printf("失败");
exit(-1);
}
pl->size = 0;
pl->capacity = 4;//初始容量
}
void clear(SL* pl)
{
assert(pl);
init(pl);
}
void destroy(SL* pl)
{
assert(pl);
free(pl->data);
free(pl);
}
void print(SL* pl)
{
assert(pl);//判断是否为null
for (int i = 0; i < pl->size; i++)
{
printf("%d ", pl->data[i]);
}
printf("\n");
}
void check(SL* pl)
{
assert(pl);
if (pl->size == pl->capacity)
{
pl->capacity = pl->capacity * 2;
pl->data = (DataType*)realloc(pl->data, sizeof(DataType) * pl->capacity);//获取两倍空间
if (pl->data == NULL)
{
printf("失败");
exit(-1);
}
}
}
void addLast(SL* pl, DataType x)
{
assert(pl);
check(pl);
add(pl, pl->size, x);
}
void add(SL* pl, int idx, DataType x)
{
assert(pl);
assert(idx <=pl->size&& idx>=0);
check(pl);
int end = pl->size - 1;
//向后移动
while (end >= idx)
{
pl->data[end + 1] = pl->data[end];
end--;
}
pl->data[idx] = x;
pl->size++;
}
DataType removeLast(SL* pl)
{
assert(pl);
return remove(pl, pl->size - 1);
}
DataType remove(SL* pl, int idx)
{
assert(pl);
assert(idx < pl->size&& idx >= 0);
DataType ans = pl->data[idx];
int start = idx;
//向前移动
while (start <= pl->size - 2)
{
pl->data[start] = pl->data[start + 1];
start++;
}
pl->size--;
return ans;
}
DataType getLast(SL* pl)
{
assert(pl);
return get(pl,pl->size - 1);
}
DataType get(SL* pl, int idx)
{
assert(pl);
assert(idx < pl->size&& idx >= 0);
return pl->data[idx];
}
int find(SL* pl, DataType x)
{
assert(pl);
for (int i = 0; i < pl->size; i++) {
if (pl->data[i] == x)
return i;
}
return -1;
}
void set(SL* pl, int idx, DataType x)
{
assert(pl);
assert(idx < pl->size&& idx >= 0);
pl->data[idx] = x;
}
int isEmpty(SL* pl)
{
return pl->size == 0 ? 1 : 0;
}
int size(SL* pl)
{
return pl->size;
}