#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//顺序表
typedef struct SeqList
{
int *array;//指向堆上空间,存放数据
int size; //有效个数
int capacity;//容量
}SeqList;
void SeqListInit(SeqList *pSeqList)
{
arrser(pSeqList != NULL);
pSeqList->capacity= 10;
pSeqList->array= (int*)malloc(sizeof (int)*pSeqList->capacity);
pSeqList->size= 0;
}
void SeqListDestroy(SeqList *pSeqList)
{
free(pSeqList->array);
pSeqList->array= NULL;
pSeqList->size= 0;
pSeqList->capacity= 0;
}
//尾插
void SeqListPushBack(SeqList *pSeqList, int value)
{
pSeqList->array[pSeqList->size]= value;
pSeqList->size++;
}
//头插
void SeqListPushFront(SeqList *pSeqList, int value)
{
for (int i = pSeqList->size- 1; i >= 0; i--)
{
pSeqList->array[i] = pSeqList ->array[i - 1];
}
pSeqList->array[0]= value;
pSeqList->size++;
}
//根据下标做插入
void SeqListInsert(SeqList *s, int pos, int v)
{
for (int i = s->size;i >= pos; i--)
{
s->array[i]= s->array[i- 1];
}
s->array[pos] = v;
s->size++;
}
//尾删
void SeqListPopBack(SeqList *ps)
{
assert(ps->size> 0);
ps->size--;
}
//头删
void SeqListPopFront(SeqList *ps)
{
for (int i = 0;i < ps->size- 1; ++i)
{
ps->array[i]= ps->array[i+ 1];
}
ps->size--;
}
//删除给定位置的数据
void SeqListErase(SeqList *ps, int pos)
{
arrars(ps->size>0);
for (int i = pos+1; i< ps->size; i++)
{
ps->array[i- 1] = ps->array[i];
}
ps->size--;
}
//假如插入式容量满了怎么办,一定需要扩容,通常来说,扩容大小是原来大小的两倍
static void CheckCapacity(SeqList *ps)
{
if (ps->size< ps->capacity)
return;
int
newcapacity = ps->capacity* 2;
int*newarray = (int*)malloc(sizeof(int)*newcapacity);
assert(newarray);
for (int i = 0;i < ps->size;i++)
{
newarray[i] = ps->array[i];
}
free(ps->array);
ps->array= newarray;
ps->capacity= newcapacity;
}
//删除遇到的第一个value
void shanchu(SeqList *ps, int value)
{
int i;
for ( i =0; i < ps->size;++i);
{
if (ps->array[i]= value)
{
ps->array[i]= ps->array[i+ 1];
}
return;
}
ps->size--;
}
//删除遇到的所有value
//其实用上面的办法也可以解决这个问题但是属于暴力破解
void SeqListRemoveAll(SeqList *ps, int value)
{
int i = 0,j = 0;
for (i; i< ps->size;i++)
{
if (ps->array[i]!= value)
{
ps->array[j]= ps->array[i];
j++;
}
}
ps->size= j;
}
顺序表基本操作
最新推荐文章于 2021-08-11 12:47:25 发布