#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int SLDataType;
//动态数据表
typedef struct SeqList {
SLDataType *a;
int size;//数组中可以存多少个数组
int capacity;//数组中空间容量
}SL;
void SeqListPrint(SL* ps);
void SeqListInit(SL* ps);
void SeqListDestory(SL* ps);
void SeqListCheckCapatcity(SL* ps);
void SeqListPushBack(SL* ps, SLDataType x);//尾插
void SeqListPopBack(SL*ps);
void SeqListPushFront(SL* ps, SLDataType x);
void SeqListPopFront(SL* ps);
//找到了返回1位置下标,没有找打返回-1;
int SeqListFind(SL* ps, SLDataType x);
void SeqListInsert(SL*ps,int pos , SLDataType x);
void SeqListErase(SL*ps,int pos );
#include"SeqList.h"
#include<assert.h>
void SeqListPrint(SL* ps) {
for (int i = 0; i < ps->size; i++) {
printf("%d ", ps->a[i]);
}
printf("\n");
}
void SeqListInit(SL* ps)
{
ps->a = NULL;
ps->size = ps->capacity = 0;
}
void SeqListDestory(SL* ps) {
free(ps->a);
ps->a = NULL;
ps->size = ps->capacity = 0;
}
void SeqListCheckCapatcity(SL* ps) {
if (ps->size == ps->capacity) {
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
SLDataType* tmp = (SLDataType*)realloc(ps->a, newcapacity * sizeof(SLDataType));
if (NULL == tmp) {
printf("failure\n");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
}
void SeqListPushBack(SL* ps, SLDataType x) {
SeqListCheckCapatcity(ps);
//ps->a[ps->size] = x;//有这两行代码才可以才会打印12345;
//ps->size++;
ps->a[ps->size++] = x;
}
void SeqListPopBack(SL* ps) {
assert(ps->size > 0);
ps->size--;
}
void SeqListPushFront(SL* ps, SLDataType x) {
SeqListCheckCapatcity(ps);
//移动数据
int end = ps->size - 1;
while (end >= 0) {//移动的下标要大于0;
ps->a[end + 1] = ps->a[end]; --end;
}
ps->a[0] = x;
ps->size++;
}
void SeqListPopFront(SL* ps) {
assert(ps->size > 0);
//这个是顺序表的头删
// 头删的话 需要把后序元素整体往前搬移 把0好位置的元素覆盖掉
int begin = 1;//这个begin意思就是下标是1的意思,可以覆盖第一个元素
while (begin < ps->size) {
ps->a[begin - 1] = ps->a[begin]; //表示把后一个位置上的元素往前一个位置上搬移
begin++;
}
ps->size--;
}
#include"SeqList.h"
void TestSeqList1() {
SL sl;
SeqListInit(&sl);
SeqListPushBack(&sl, 1);
SeqListPushBack(&sl, 2);
SeqListPushBack(&sl, 3);
SeqListPushBack(&sl, 4);
SeqListPushBack(&sl, 5);
SeqListPrint(&sl);
SeqListPushFront(&sl, 10);
SeqListPushFront(&sl, 20);
SeqListPushFront(&sl, 30);
SeqListPushFront(&sl, 40);
SeqListPrint(&sl);
SeqListPopFront(&sl);
SeqListPopFront(&sl);
SeqListPopFront(&sl);
SeqListPopFront(&sl);
SeqListPrint(&sl);
SeqListDestory(&sl);
}
int main() {
TestSeqList1();
return 0;
}