顺序表(C语言)

顺序表是⽤⼀段物理地址连续的存储单元依次存储数据元素的线性结构,⼀般情况下采⽤数组
存储。

静态顺序表

使用定长数组存储元素
缺陷:给少了不够用,给多了造成空间浪费
typedef int SLDataType;
#define N 7;
typedef struct SeqList{
    SLDataType a[N];
    int size;
}SL;

动态顺序表

按需求申请

typedef struct SeqList
{
    SLDataType *a;
    int size;     //有效数据个数
    int capacity; //空间容量
}SL;

 动态顺序表的实现

1、定义顺序表的结构

typedef int SLDatatype;

typedef struct SeqList {
	SLDatatype* arr;
	int capacity; //空间大小
	int size;     //有效数据个数
}SL;

2、初始化

void SLInit(SL* ps)
{
	ps->arr = NULL; //让arr置为空
	ps->size = ps->capacity = 0;//有效数据个数和空概念容量也为0
}

3、 销毁顺序表

void SLDestroy(SL* ps)
{
	if (ps->arr)//只有arr不为空才能释放空间
	{
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

4、打印顺序表元素

void SLPrint(SL* ps)
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\n");
}

5、检查当前空间是否足够并扩容 

void SLCheckCapacity(SL* ps)
{
	//判断空间是否充足
	if (ps->size == ps->capacity)
	{
		//增容//0*2 = 0
		//若capacity为0,给个默认值,否则×2倍
		int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SLDatatype* tmp = (SLDatatype*)realloc(ps->arr, newCapacity * sizeof(SLDatatype));
        //若开辟空间失败则退出程序
		if (tmp == NULL)
		{
			perror("realloc fail!");
			exit(1);
		}
		ps->arr = tmp;
        //更新空间容量
		ps->capacity = newCapacity;
	}
}

6、 插入数据

尾插

void SLPushBack(SL* ps, SLDatatype x)
{
	assert(ps);//等价于assert(ps != NULL)
    //检查空间是否足够
	SLCheckCapacity(ps);
	ps->arr[ps->size++] = x;
}

 

头插

void SLPushFront(SL* ps, SLDatatype x)
{
	assert(ps);
	//判断空间是否足够
	SLCheckCapacity(ps);
	
	//数据整体后移一位
	for (int i = ps->size; i > 0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	//下标为0的位置空出来
	ps->arr[0] = x;

	ps->size++;
}

 

 在指定位置之前插入数据

void SLInsert(SL* ps, SLDatatype x, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);

	SLCheckCapacity(ps);

	//pos及之后的数据整体向后移动一位
	for (int i = ps->size; i > pos  ; i--)
	{
		ps->arr[i] = ps->arr[i - 1]; //pos+1   ->   pos
	}
	
	ps->arr[pos] = x;
	ps->size++;
}

 

 7、删除数据

尾删

void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->size);
    //直接让有效空间个数向前一位
	ps->size--;
}

头删

void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size);

	//数据整体向前挪动一位
	for ( int i = 0; i < ps->size - 1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];//i = size-2
	}
	ps->size--;
}

 删除指定位置数据

void SLErase(SL* ps,int pos)
{
assert(ps);
assert(pos >= 0 && pos < ps->size);
//pos之后的所有数据向前移动一位
for(int i = pos; i < ps->size-1; i++)
{
  ps->arr[i] = ps->arr[i+1];
}
ps->sie--;

 

 8、查找元素

int SLFind(SL* ps,SLDatatype x)
{
  assert(ps);
  for(int i=0;i < ps->size; i++)
  {
     if(ps->arr[i] == x)
        {
          //如果能查得到元素就返回下标
          return i;
        }
  }
  //没找到就返回-1
  return -1;
}

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值