开始研究数据结构了:
顺序表
顺序表是小白们广泛使用的一种数据结构,其特点是数据在物理空间上依旧是连续存放的,所有元素都是线性保存的,比如数组就是一种典型的顺序表,实际上顺序表也大多都用数组来储存.
最简单的顺序表应该包括:数据,容量,有效数据元素.有了这几个元素,操作顺序表时比较方便
如何构造和操作顺序表:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int DataType;
#define MAX_SIZE 100
typedef struct SeqList {
DataType* _arry;//保存数据
int _capacity; //顺序表总大小
int _size;//有效元素个数
}Seqlist, *Pseq;
void SeqlistInit(Pseq ps, int capacity) {//初始化顺序表
ps->_arry = (DataType*)malloc(sizeof(DataType)*capacity);
if (NULL == ps->_arry){
assert(0);
return;
}
ps->_capacity = capacity;
ps->_size = 0;
}
void SeqlistDestory(Pseq ps) {//销毁顺序表
if (ps->_arry){
free(ps->_arry);
ps->_arry = NULL;
ps->_capacity = 0;
ps->_size = 0;
}
}
void SeqListPushBack(Pseq ps, DataType data) {//在顺序表尾部插入元素
assert(ps);
ps->_arry[ps->_size] = data;
ps-> _size++;
}
int SeqListEmpty(Pseq ps) {//判断顺序表是否为空,要写在所有调用了这个函数的函数之前,否则会报错
assert(ps);
return (0 == ps->_size);
}
void SeqListPopBack(Pseq ps) {//删除顺序表尾部元素
assert(ps);
if (SeqListEmpty(ps)) {
return;
}
ps->_size--;
}
void SeqListPushFront(Pseq ps, DataType data) {//在顺序表前插入元素
assert(ps);
for (int i = ps->_size - 1; i >= 0; --i) {
ps->_arry[i + 1] = ps->_arry[i];
}
ps->_arry[0] = data;
++ps->_size;
}
void SeqListPopFront(Pseq ps) {//删除顺序表第一个元素
if (SeqListEmpty(ps)) {
return;
}
for (int i = 1; i <= ps->_size - 1; ++i) {
ps->_arry[i - 1] = ps->_arry[i];
}
ps->_size--;
}
void SeqlistInsert(Pseq ps, int pos, DataType data) {//在指定位置插入元素
assert(ps);
if (pos<0 || pos>ps->_size) {
return;
}
for (int i = ps->_size - 1; i >= pos; --i) {
ps->_arry[i + 1] = ps->_arry[i];
}
ps->_arry[pos] = data;
ps->_size++;
}
void SeqListErase(Pseq ps, int pos) {//删除指定位置元素
assert(ps);
if (pos < 0 || pos >= ps->_size) {
return;
}
for (int i = pos + 1; i < ps->_size; ++i) {
ps->_arry[i - 1] = ps->_arry[i];
}
ps->_size--;
}
int SeqListSize(Pseq ps) {//查看顺序表元素个数
assert(ps);
printf("顺序表共 %d 个有效元素\n", ps->_size);
return ps->_size;
}
int SeqListCapacity(Pseq ps) {//查看顺序表大小
assert(ps);
printf("顺序表的容量大小为:%d\n", ps->_capacity);
return ps->_capacity;
}
void SeqListClear(Pseq ps) {//将顺序表的所有元素清零
assert(ps);
for (int i = 0; i < ps->_size; ++i) {
ps->_arry[i] = 0;
}
return ;
}
void SeqlistRemove(Pseq ps,int find) {//删除顺序表第一个找到的元素X
int i;
for (i = 0; i < ps->_size; ++i) {
if (ps->_arry[i]==find){
SeqListErase(ps, i);
break;
}
}
if (i == ps->_size) {
printf("未寻获 %d\n", find);
return;
}
}
void SeqListPrint(Pseq ps) {//打印顺序表
for (int i = 0; i < ps->_size; ++i) {
printf("%d ", ps->_arry[i]);
}
printf("\n");
}
int main (){
Seqlist s;
SeqlistInit(&s, 10);
SeqListPushBack(&s, 1);
SeqListPushBack(&s, 2);
SeqListPushBack(&s, 3);
SeqListPushBack(&s, 4);
SeqListPushBack(&s, 5);
SeqListPrint(&s);
SeqListPopBack(&s);
SeqListPrint(&s);
SeqListPushFront(&s, 0);
SeqListPrint(&s);
SeqListPopFront(&s);
SeqListPrint(&s);
SeqListSize(&s);
SeqListCapacity(&s);
SeqlistRemove(&s, 3);
SeqListPrint(&s);
system("pause");
return 0;
}