#include"seqlist.h"
int main()
{
Seqlist list;
SeqlistInit(&list);
SeqlistPushfront(&list, 1);
SeqlistPushfront(&list, 2);
SeqlistPushfront(&list, 3);
SeqlistPushfront(&list, 4);
SeqlistPushback(&list, 5);
SeqlistPrint(&list);
return 0;
}
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef int Datetype;
typedef struct Seqlist
{
Datetype* a;
int size;
int capacity;
}Seqlist;
void SeqlistInit(Seqlist* ps);
void SeqlistDestroy(Seqlist* ps);
void SeqlistPrint(Seqlist* ps);
void SeqlistPushfront(Seqlist* ps, Datetype x);
void SeqlistPushback(Seqlist* ps, Datetype x);
void SeqlistPopfront(Seqlist* ps);
void SeqlistPopback(Seqlist* ps);
// 顺序表查找
int SeqlistFind(Seqlist* ps, Datetype x);
// 顺序表在pos位置插入x
void SeqListInsert(Seqlist* ps, int pos, Datetype x);
// 顺序表删除pos位置的值
void SeqListErase(Seqlist* ps, int pos);
#include"seqlist.h"
void SeqlistInit(Seqlist* ps)
{
assert(ps);
ps->a = NULL;//刚开始时顺序表为空,顺序表指针为NULL
ps->size = 0;//起始时元素个数为0
ps->capacity = 0;//容量为0
}
void SeqlistDestroy(Seqlist* ps)
{
assert(ps);
free(ps);
ps->a = NULL;
ps->capacity = ps->size = 0;
}
void SeqlistPrint(Seqlist* ps)
{
assert(ps);
for (size_t i = 0; i<ps->size; i++)
{
printf("%d ", ps->a[i]);
}
printf("\n");
}
void SeqCkeckcapacity(Seqlist* ps)
{
if (ps->capacity == ps->size)
{
int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
Datetype* newlist = realloc(ps->a, newcapacity * sizeof(Datetype));
if (newlist == NULL)
{
perror("realloc fail");
}
ps->a = newlist;
ps->capacity = newcapacity;
}
}
void SeqlistPushfront(Seqlist* ps, Datetype x)
{
/*assert(ps);
SeqCkeckcapacity(ps);
for (int i = ps->size; i > 0; i--)
{
ps->a[i] = ps->a[i-1];
}
ps->a[0] = x;
ps->size++;*/
SeqListInsert(ps, 0, x);
}
void SeqlistPushback(Seqlist* ps, Datetype x)
{
/*assert(ps);
SeqCkeckcapacity(ps);
ps->a[ps->size] = x;
ps->size++;*/
SeqListInsert(ps, ps->size, x);
}
void SeqlistPopfront(Seqlist* ps)
{
assert(ps);
for (int i = 0; i < ps->size - 1; i++)
{
ps->a[i] = ps->a[i + 1];
}
ps->size--;
}
void SeqlistPopback(Seqlist* ps)
{
assert(ps);
assert(ps->size > 0);
ps->size--;
}
// 顺序表查找
int SeqlistFind(Seqlist* ps, Datetype x)
{
assert(ps);
for (int i = 0; i < ps->size; i++)
{
if (ps->a[i] == x)
{
return i;
}
}
return -1;
}
// 顺序表在pos位置插入x
void SeqListInsert(Seqlist* ps, int pos, Datetype x)
{
assert(ps);
assert(pos >= 0 && pos <= ps->size);
SeqCkeckcapacity(ps);
for (int i = ps->size; i > pos; i--)
{
ps->a[i] = ps->a[i - 1];
}
ps->a[pos] = x;
ps->size++;
}
// 顺序表删除pos位置的值
void SeqListErase(Seqlist* ps, int pos)
{
assert(ps);
assert(ps->size > 0);
assert(pos >= 0 && pos < ps->size);
for (int i = pos; pos < ps->size-1; i++)
{
ps->a[i] = ps->a[i + 1];
}
ps->size--;
}