学习数据结构和算法的第8天

顺序表的实现

进行头插

eg:在数组 1 2 3 4 5的开头插入-1

变成-1 1 2 3 4 5

c 复制代码
#include<stdio.h>
typedef struct SeqList {
    SLDataType a[100]; // 假设顺序表最大容量为100
    int size; // 当前顺序表的大小
} SL;
void SeqListPushFront(SL* ps, SLDataType x)
{
    int end = ps->size-1;
    while (end >= 0) {
        ps->a[end+1] = ps->a[end];
        --end;
    }
    ps->a[0] = x;
    ps->size++;
}
int main()
{
    SL seqList; // 创建一个顺序表对象
    seqList.size = 0; // 初始化顺序表的大小为0
    // 向顺序表的开头插入元素
    SeqListPushFront(&seqList, 10);
    SeqListPushFront(&seqList, 20);
    SeqListPushFront(&seqList, 30);
    // 打印顺序表中的元素
    for (int i = 0; i < seqList.size; i++) {
        printf("%d ", seqList.a[i]);
    }
    printf("\n");
    
    return 0;
}

头删

eg:数组1 2 3 4 5

删去1

c 复制代码
#include <stdio.h>
typedef struct SeqList {
    SLDataType a[100];
    int size;
} SL;
void SeqListRemoveFront(SL* ps)
{
    if (ps->size <= 0) {
        // 顺序表为空,无法进行头删操作
        return;
    }
    for (int i = 0; i < ps->size - 1; i++) {
        ps->a[i] = ps->a[i + 1];
    }
    ps->size--;
}
int main()
{
    SL seqList;
    seqList.size = 0;
    // 添加一些元素到顺序表
    seqList.a[0] = 10;
    seqList.a[1] = 20;
    seqList.a[2] = 30;
    seqList.size = 3;
    // 执行头删操作
    SeqListRemoveFront(&seqList);
    // 打印顺序表中的元素
    for (int i = 0; i < seqList.size; i++) {
        printf("%d ", seqList.a[i]);
    }
    printf("\n");
    return 0;
}
相关推荐
时光话14 分钟前
Lua 第14部分 数据结构
开发语言·数据结构·lua
地平线开发者25 分钟前
C++ 部署的性能优化方法
c++·算法·自动驾驶
怀念无所不能的你27 分钟前
acwing背包问题求方案数
学习·算法·动态规划·dp
Yingye Zhu(HPXXZYY)1 小时前
洛谷P12238 [蓝桥杯 2023 国 Java A] 单词分类
c++·算法·蓝桥杯
LVerrrr1 小时前
Missashe考研日记-day29
学习·考研
灏瀚星空1 小时前
从基础到实战的量化交易全流程学习:1.3 数学与统计学基础——线性代数与矩阵运算 | 矩阵基础
笔记·python·学习·线性代数·数学建模·金融·矩阵
Phoebe鑫1 小时前
数据结构每日一题day13(链表)★★★★★
数据结构·链表
Seven971 小时前
缓存穿透的解决方式?—布隆过滤器
java·数据结构·redis
qq_162911591 小时前
tigase源码学习杂记-IO处理的线程模型
java·学习·源码·xmpp·tigase·多线程io模型
viperrrrrrrrrr71 小时前
大数据学习(115)-hive与impala
大数据·hive·学习·impala