#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
//将SLDataType的数据类型设为int
typedef int SLDataType;
//SeqList == SL
typedef struct SeqList {
//首元素地址
SLDataType* arr;
//已有数据个数
int size;
//最大容量
int capacity;
}SL;
//初始化
void SLInit(SL* psl);
//销毁
void SLDestroy(SL* psl);
//打印
void SLPrint(SL* psl);
//尾插
void SLPushBack(SL* psl, SLDataType x);
//尾删
void SLPopBack(SL* psl);
//头插
void SLPushFront(SL* psl,SLDataType x);
//头删
void SLPopFront(SL* psl);
//在pos位置插入
void SLInsert(SL* psl, int pos, SLDataType x);
//在pos位置删除
void SLErase(SL* psl, int pos);
//扩容
void SLCheckCapacity(SL* psl) {
if (psl->size == psl->capacity) {
psl->capacity = 2 * psl->capacity + 1;
SLDataType* tmp = (SLDataType*)realloc(psl->arr, psl->capacity * sizeof(SLDataType));
if (tmp == NULL) {
perror("SLPushBack.increase capacity is fail");
exit(-1);
}
psl->arr = tmp;
printf("increase capacity is success!\n");
}
}
void SLInit(SL* psl) {
assert(psl);
psl->arr = NULL;
psl->size = 0;
psl->capacity = 0;
}
void SLDestroy(SL* psl) {
assert(psl);
free(psl->arr);
psl->arr = NULL;
psl->size = 0;
psl->capacity = 0;
}
void SLPrint(SL* psl) {
assert(psl);
for (int i = 0; i < psl->size; i++) {
printf("%d ", psl->arr[i]);
}
printf("\n");
}
void SLPushBack(SL* psl, SLDataType x) {
assert(psl);
//位置不够就扩容
SLCheckCapacity(psl);
psl->arr[psl->size] = x;
psl->size++;
}
void SLPopBack(SL* psl) {
assert(psl->size > 0);
if (psl->size == 0) {
printf("顺序表已空!\n");
}
else {
psl->size--;
}
}
void SLPushFront(SL* psl, SLDataType x) {
assert(psl);
//位置不够就扩容
SLCheckCapacity(psl);
int end = psl->size - 1;
while (end >= 0) {
psl->arr[end + 1] = psl->arr[end];
end--;
}
psl->arr[0] = x;
psl->size++;
}
void SLPopFront(SL* psl) {
assert(psl);
//判断表是否为空
assert(psl->size>0);
int i = 0;
for (i = 0; i < psl->size - 1; i++) {
psl->arr[i] = psl->arr[i + 1];
}
psl->size--;
}
void SLInsert(SL* psl, int pos, SLDataType x) {
assert(psl);
assert(pos >= 0);
assert(pos <= psl->size);
SLCheckCapacity(psl);
int end = psl->size - 1;
for (end; end >= pos; end--) {
psl->arr[end + 1] = psl->arr[end];
}
psl->arr[pos] = x;
psl->size++;
}
void SLErase(SL* psl, int pos) {
assert(psl);
assert(pos >= 0);
assert(pos < psl->size);
for (pos; pos < psl->size - 1; pos++) {
psl->arr[pos] = psl->arr[pos + 1];
}
psl->size--;
}
int SLFind(SL* psl, SLDataType x) {
assert(psl);
int i = 0;
for (i; i < psl->size; i++) {
if (psl->arr[i] == x) {
return i;
}
}
return -1;
}
int SLFind2(SL* psl, SLDataType x, int pos) {
assert(psl);
for (pos; pos < psl->size; pos++) {
if (psl->arr[pos] == x) {
return pos;
}
}
return -1;
}
C语言数据结构——顺序表
最新推荐文章于 2024-06-16 00:05:12 发布