1. 顺序表
1.1 概念与结构
概念:顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,⼀般情况下采⽤ 数组存储。
1.2顺序表和数组的区别?
顺序表的底层结构是数组,对数组的封装,实现了常⽤的增删改查等接口。
2 .分类
2.1 静态顺序表
概念:使用定长数组存储元素z
#pragma once
#include<stdio.h>
#define N 1000
typedef int SLDataType;
typedef struct seqlist
{
SLDataType arr[N];
int size; //有效数据个数
}SL;
缺点:空间给小,不够用,给大了还浪费,不好。
2.2 动态顺序表
优点:可以动态申请空间
#pragma once
#include<stdio.h>
#define N 1000
typedef int SLDataType;
typedef struct seqlist
{
SLDataType* arr;
int capacity; //容量
int size; //有效数据个数
}SL;
3.用顺序表实现头/尾(插/删)
在这里,为了避免一个文件中代码过于庞大,我们改用三个文件分开写,同时也方便我们查找之前写过的函数。
在进行头尾插删操作时,一定要结合图形,会事半功倍,重点是画图!
首先我们创建一个头文件,seqlist.h
#include<stdio.h>
#include<assert.h>
#include <stdlib.h>
typedef int sltype; //自定义类型
typedef struct seqlist //创建动态表
{
int size;
int capacity;
sltype* arr;
}sl;
void slinit(sl* ps);
void checkcapacity(sl* ps);
void pushfront(sl* ps, sltype x); //头插
void popback(sl* ps); //尾删
void pushback(sl* ps,sltype x); //尾插
void popfront(sl* ps); //头删
void slinspop(sl* ps, int pos); //指定位置删除
void slinsert(sl* ps, int pos, int x); //指定位置插入
void slprint(sl* ps); //打印
在创建一个seqlist.c文件
#include"seqlist.h"
//进行初始化
void slinit(sl* ps)
{
ps->size = ps->capacity = 0;
ps->arr = NULL;
}
//扩容申请空间
void checkcapacity(sl* ps)
{
if (ps->size == ps->capacity)
{
int newcp = ps->capacity == 0 ? 4 : ps->capacity * 2;
sltype* tmp = (sltype*)realloc(ps->arr, newcp * sizeof(sltype));
assert(tmp);
ps->arr = tmp;
ps->capacity = newcp;
}
}
//头插
void pushfront(sl* ps,sltype x)
{
assert(ps);
checkcapacity(ps);
for (int i = ps->size; i > 0; i--)
{
ps->arr[i] = ps->arr[i - 1];
}
ps->arr[0] = x;
++ps->size;
}
//尾删
void popback(sl* ps)
{
assert(ps && ps->size);
ps->size--;
}
//尾插
void pushback(sl* ps,sltype x)
{
assert(ps);
checkcapacity(ps);
ps->arr[ps->size] = x;
ps->size++;
}
//头删
void popfront(sl* ps)
{
assert(ps && ps->size);
for (int i = 0; i < ps->size-1; i++)
{
ps->arr[i] = ps->arr[i + 1];
}
ps->size--;
}
//指定位置删除
void slinspop(sl* ps, int pos)
{
for (int i = pos; i < ps->size - 1; i++)
{
ps->arr[i] = ps->arr[i + 1];
}
ps->size--;
}
//指定位置插入
void slinsert(sl* ps, int pos, int x)
{
assert(ps);
checkcapacity(ps);
for (int i = ps->size-1; i > pos; i--)
{
ps->arr[i + 1] = ps->arr[i];
}
ps->arr[pos] = x;
ps->size++;
}
//打印函数
void slprint(sl* ps)
{
for (int i = 0; i < ps->size; i++)
{
printf("%d", ps->arr[i]);
}
printf("\n");
}
最后我们在创建test.c文件调用一下
#include"seqlist.h"
void sltest()
{
sl s1;
slinit(&s1); //别忘了初始化
//头插
pushfront(&s1, 1);
slprint(&s1);
pushfront(&s1, 2);
slprint(&s1);
pushfront(&s1, 3);
slprint(&s1);
//尾删
popback(&s1);
slprint(&s1);
popback(&s1);
slprint(&s1);
popback(&s1);
slprint(&s1);
//尾插
pushback(&s1, 1);
slprint(&s1);
pushback(&s1, 2);
slprint(&s1);
pushback(&s1, 3);
slprint(&s1);
//头删
popfront(&s1);
slprint(&s1);
popfront(&s1);
slprint(&s1);
popfront(&s1);
slprint(&s1);
//指定位置删除
slinspop(&s1, 1);
slprint(&s1);
//指定位置插入
slinsert(&s1, 1, 2);
slprint(&s1);
}
int main()
{
sltest();
return 0;
}
如此,我们便完成了头尾插删。

346

被折叠的 条评论
为什么被折叠?



