[数据结构]——顺序表的实现(初始化销毁打印检查容量尾插尾删头插头删)
Posted FortunateJA
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[数据结构]——顺序表的实现(初始化销毁打印检查容量尾插尾删头插头删)相关的知识,希望对你有一定的参考价值。
SeqList.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
typedef int SLDatatype;
typedef struct SeqList
SLDatatype *a; //指向动态开辟的数组
int size; //有效数据个数
int capacity; //容量空间大小
SeqList;
void SeqListInit(SeqList *psl); //初始化
void SeqListDestory(SeqList *psl); //销毁
void SeqListPrint(SeqList *psl); //打印
void CheckCapacity(SeqList *psl); //检擦容量是否满了
void SeqListPushBack(SeqList *psl, SLDatatype x); //尾插
void SeqListPopBack(SeqList *psl); //尾删
void SeqListPushFront(SeqList *psl, SLDatatype x); //头插
void SeqListPopFront(SeqList *psl); //头删
SeqList.c
#include "SeqList.h"
/*
typedef int SLDatatype;
typedef struct SeqList
SLDatatype *a;
int size;
int capacity;
SeqList;
*/
void SeqListInit(SeqList *psl) //初始化
psl->a = (SLDatatype*)malloc(sizeof(SLDatatype)* 4); //开辟四个空间
if (psl->a == NULL) //判断是否开辟成功
printf("malloc fail\\n");
exit(-1);
memset(psl->a, 0, sizeof(SLDatatype)* 4); //开辟的四个空间的数值均置为0
psl->capacity = 4; //容量为四
psl->size = 0; //有效数据个数为0
void SeqListDestory(SeqList *psl) //销毁
free(psl->a); //释放在初始化时开辟的空间
psl->a = NULL;
psl->capacity = psl->size = 0;
void SeqListPrint(SeqList *psl) //打印
for (int i = 0; i < psl->size; i++)
printf("%d ", psl->a[i]);
printf("\\n");
void CheckCapacity(SeqList *psl) //检擦容量是否满了
if (psl->capacity == psl->size) //空间不够需要增容
SLDatatype *tmp = realloc(psl->a, sizeof(SLDatatype)*psl->capacity * 2); //原地增容
if (tmp == NULL) //如果增容失败,则退出
printf("realloc fail\\n");
exit(-1);
//增容成功,则将指针指向新开辟的空间
psl->a = tmp;
psl->capacity = psl->capacity * 2;
void SeqListPushBack(SeqList *psl, SLDatatype x) //尾插
assert(psl);
CheckCapacity(psl); //判断空间是否满了
psl->a[psl->size] = x;
psl->size++;
void SeqListPopBack(SeqList *psl) //尾删
assert(psl);
assert(psl->size > 0); //此处要进行判断,顺序表中有效数据是否大于0,不大于0不可删除
psl->size--;
void SeqListPushFront(SeqList *psl, SLDatatype x) //头插
assert(psl);
CheckCapacity(psl);
int end = psl->size - 1;
while (end >= 0)
psl->a[end + 1] = psl->a[end];
end--;
psl-> a[0] = x;
psl->size++;
void SeqListPopFront(SeqList *psl) //头删
assert(psl);
assert(psl->size > 0);
int begin = 1;//挪动数据,把第一个数据覆盖掉
while (begin < psl->size)
psl->a[begin - 1] = psl->a[begin];
begin++;
psl->size--;
Test.c
#include"SeqList.h"
int main()
SeqList s;
SeqListInit(&s);
SeqListPushBack(&s, 1);
SeqListPushBack(&s, 2);
SeqListPushBack(&s, 3);
SeqListPushBack(&s, 4);
SeqListPushBack(&s, 5);
printf("PushBack:");
SeqListPrint(&s);
SeqListPushFront(&s, 11);
SeqListPushFront(&s, 12);
SeqListPushFront(&s, 13);
printf("PushFront:");
SeqListPrint(&s);
SeqListPopFront(&s);
printf("PopFront:");
SeqListPrint(&s);
SeqListPopBack(&s);
printf("PopBack:");
SeqListPrint(&s);
SeqListDestory(&s);
return 0;
测试结果
以上是关于[数据结构]——顺序表的实现(初始化销毁打印检查容量尾插尾删头插头删)的主要内容,如果未能解决你的问题,请参考以下文章