数据结构 顺序表 实现增添删减
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef int SLDateType;
typedef struct SeqList
{
SLDateType* a;
int size;//有效数据个数·
int capacity;//容量
}SeqList;
void SeqListInit(SeqList* ps)//初始化
{
ps->a=(SLDateType*)malloc(sizeof(SLDateType)*4);
if(ps->a==NULL)
{
printf("申请内存失败\n");
exit(-1);//直接结束
}
ps->size = 0;
ps->capacity = 4;
}
void SeqListCheckCapacity(SeqList* ps)//判断是否需要扩容
{
if(ps->size >= ps->capacity)
{
ps->capacity*=2;//扩为原来两倍
ps->a = (SLDateType*)realloc(ps->a,sizeof(SLDateType)*ps->capacity);
if(ps->a==NULL)
{
printf("申请内存失败\n");
exit(-1);//直接结束
}
}
}
void SeqListPrint(SeqList* ps)//打印
{
int i;
for(i=0;i<ps->size;++i)
{
printf("%d ",ps->a[i]);
}
printf("\n");
}
void SeqListPushBack(struct SeqList* ps,SLDateType x)//尾加
{
//得考虑是否满了,满了就得增容
SeqListCheckCapacity(ps);
ps->a[ps->size] = x;
ps->size++;
}
void SeqListPopBack(struct SeqList* ps)//尾删
{
ps->size--;
}
void SeqListPushFront(struct SeqList* ps,SLDateType x)//头插
{
int i;
for(i=ps->size-1;i>=0;i--)
{
ps->a[i+1]=ps->a[i];
}
ps->a[0]=x;
ps->size++;
}
void SeqListPopFront(struct SeqList* ps)//头减
{
int i;
for(i=1;i<ps->size;i++)
{
ps->a[i-1]=ps->a[i];
}
ps->size--;
}
void TestSeqList1()
{
SeqList s;
SeqListInit(&s);
SeqListPushBack(&s,1);
SeqListPushBack(&s,2);
SeqListPushBack(&s,3);
SeqListPushBack(&s,4);
SeqListPushBack(&s,5);
SeqListPushBack(&s,6);
SeqListPushBack(&s,7);
SeqListPushBack(&s,8);
SeqListPushBack(&s,9);
SeqListPrint(&s);
SeqListPopBack(&s);
SeqListPopBack(&s);
SeqListPrint(&s);
SeqListPushFront(&s,0);
SeqListPushFront(&s,-1);
SeqListPrint(&s);
SeqListPopFront(&s);
SeqListPopFront(&s);
SeqListPopFront(&s);
SeqListPrint(&s);
}
int main()
{
TestSeqList1();
return 0;
}