#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#define INIT_CAPACITY 4
typedef int SLDatatype;
typedef struct SeqList
{
SLDatatype* a;
int size;
int capacity;
}SL;
void SeqListInit(SL* ps);
void SeqListDestroy(SL* ps);
void SeqListPrint(SL* ps);
void SeqListPushBack(SL* ps, SLDatatype x);
void SeqListPopBack(SL* ps);
void SeqListPushFront(SL* ps, SLDatatype x);
void SeqListPopFront(SL* ps);
//顺序表扩容
void SeqListcapacity(SL* ps);
// 顺序表查找
int SeqListFind(SL* ps, SLDatatype x);
// 顺序表在pos位置插入x
void SeqListInsert(SL* ps, int pos, SLDatatype x);
// 顺序表删除pos位置的值
void SeqListErase(SL* ps, int pos);
void SeqListInit(SL* ps)
{
assert(ps);
ps->a = (SLDatatype*)malloc(sizeof(SLDatatype) * INIT_CAPACITY);
if (ps->a == NULL)
{
perror("malloc fail");
return;
}
ps->size = 0;
ps->capacity = INIT_CAPACITY;
}
void SeqListcapacity(SL*ps)
{
assert(ps);
if (ps->size == ps->capacity)
{
SLDatatype* tmp = (SLDatatype*)realloc(ps->a, sizeof(SLDatatype) * ps->capacity * 2);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity *= 2;
}
}
void SeqListDestroy(SL* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = ps->size = 0;
}
void SeqListPrint(SL* ps)
{
assert(ps);
for (int i = 0;i < ps->size;i++)
{
printf("%d ", ps->a[i]);
}
printf("\n");
}
void SeqListPushBack(SL* ps, SLDatatype x)
{
assert(ps);
SeqListcapacity(ps);
ps->a[ps->size++] = x;
}
void SeqListPopBack(SL* ps)
{
assert(ps);
if (ps->size == 0)
{
return;
}
ps->size--;
}
void SeqListPushFront(SL* ps, SLDatatype x)
{
assert(ps);
SeqListcapacity(ps);
int end = ps->size;
while (end > 0)
{
ps->a[end] = ps->a[end-1];
end -- ;
}
ps->a[0] = x;
ps->size++;
}
void SeqListPopFront(SL* ps)
{
assert(ps);
int start = 0;
while (start < ps->size - 1)
{
ps->a[start] = ps->a[start + 1];
start++;
}
ps->size--;
}
int SeqListFind(SL* ps, SLDatatype x)
{
assert(ps);
int i = 0;
for (i = 0;i < ps->size;i++)
{
if (ps->a[i] == x)
return i;
}
return;
}
void SeqListInsert(SL* ps, int pos, SLDatatype x)
{
assert(ps);
SeqListcapacity(ps);
assert(pos <= ps->size);
int end = ps->size;
while (end > pos)
{
ps->a[end ] = ps->a[end-1];
end--;
}
ps->a[pos] = x;
ps->size++;
}
void SeqListErase(SL* ps, int pos)
{
assert(ps);
SeqListcapacity(ps);
int start= pos+1;
while (start <ps->size)
{
ps->a[start -1] = ps->a[start];
start--;
}
ps->size--;
}
void seqlist()
{
SL sl;
SeqListInit(&sl);
SeqListPushFront(&sl,1);
SeqListPushFront(&sl,2);
SeqListPushFront(&sl,3);
SeqListPushFront(&sl,4);
/*SLDatatype ret = SeqListFind(&sl, 4);
printf("%d\n", sl.a[ret]);*/
SeqListInsert(&sl, 2, 1);
//SeqListErase(&sl, 2);
SeqListPrint(&sl);
SeqListDestroy(&sl);
}
int main()
{
seqlist();
return 0;
}