首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >C语言算法宝库:从基础数据结构到经典算法实现

C语言算法宝库:从基础数据结构到经典算法实现

原创
作者头像
qife122
发布2026-02-02 13:35:09
发布2026-02-02 13:35:09
900
举报

项目标题与描述

这是一个用C语言实现的综合性算法和数据结构库,收集了从基础到高级的多种算法实现。项目遵循GPLv3许可证,覆盖计算机科学、数学统计、数据科学、机器学习、工程学等多个领域的算法。

该项目的主要目标是提供一个教育性的资源,帮助学习者和开发者理解算法和数据结构的原理与实现。所有代码都经过精心设计和测试,确保正确性和可读性。

功能特性

音频处理

  • A-law编码解码:实现G.711标准中的A-law算法,用于16位PCM音频的压缩和解压缩

加密算法

  • 仿射密码:使用线性变换进行字母替换的加密算法
  • ROT13密码:简单的字母替换密码,每个字母替换为字母表中13位后的字母

客户端-服务器通信

  • TCP全双工通信:客户端和服务器可以同时发送和接收数据
  • TCP半双工通信:客户端和服务器可以发送数据但每次只能一方发送
  • UDP客户端-服务器:基于UDP协议的简单通信模型
  • 远程命令执行:通过UDP实现远程命令执行功能

进制转换

  • 二进制转十进制/十六进制/八进制:多种进制间的相互转换
  • 十进制转二进制/十六进制/八进制:支持递归和迭代实现
  • 罗马数字转十进制:将罗马数字转换为十进制数值

数据结构

  • 数组:动态数组和静态数组实现
  • :数组实现和链表实现的栈
  • 队列:链表实现的队列,包括优先级队列
  • 链表:单向链表、双向链表、循环链表
  • 哈希表:简单的字典实现
  • 哈希集合:动态哈希集合
  • 树结构:二叉树、AVL树、红黑树、二叉搜索树、线索二叉树
  • :最大堆和最小堆实现
  • 段树:支持范围查询的数据结构

图算法

  • 广度优先搜索(BFS):图的广度优先遍历
  • 深度优先搜索(DFS):图的深度优先遍历
  • 迪杰斯特拉算法:单源最短路径算法
  • 贝尔曼-福特算法:处理负权边的最短路径算法
  • 弗洛伊德-沃舍尔算法:所有节点对最短路径算法
  • 克鲁斯卡尔算法:最小生成树算法
  • 拓扑排序:有向无环图的线性排序
  • 强连通分量:查找有向图的强连通分量
  • 哈密顿路径:查找图中是否存在哈密顿路径
  • 欧拉路径:查找图中是否存在欧拉路径

表达式转换

  • 中缀转后缀:将中缀表达式转换为后缀表达式

安装指南

系统要求

  • C编译器(如gcc、clang)
  • 标准C库
  • 对于Windows平台,需要Winsock2库

编译步骤

  1. 克隆项目到本地:git clone https://github.com/TheAlgorithms/C.git
  2. 进入项目目录:cd C
  3. 编译单个算法文件:gcc -o algorithm_name algorithm_file.c
  4. 运行程序:./algorithm_name

平台注意事项

  • 对于Windows平台,代码中已经包含了相应的平台适配
  • 部分网络编程相关代码需要管理员权限运行
  • 建议使用C99或更高标准的编译器

使用说明

基础使用示例

以下是几个核心算法的使用示例:

A-law音频编码解码
代码语言:c
复制
#include <stdio.h>
#include "audio/alaw.c"

int main() {
    int16_t pcm[] = {1000, -1000, 1234, 3200};
    uint8_t alaw[4];
    int16_t decoded[4];
    
    // 编码
    encode(alaw, pcm, 4);
    
    // 解码
    decode(decoded, alaw, 4);
    
    return 0;
}
仿射密码
代码语言:c
复制
#include <stdio.h>
#include "cipher/affine.c"

int main() {
    char text[] = "Hello World!";
    affine_key_t key = {7, 11};
    
    printf("原始文本: %s\n", text);
    
    // 加密
    affine_encrypt(text, key);
    printf("加密后: %s\n", text);
    
    // 解密
    affine_decrypt(text, key);
    printf("解密后: %s\n", text);
    
    return 0;
}
二叉树操作
代码语言:c
复制
#include <stdio.h>
#include "data_structures/binary_trees/basic_operations.c"

int main() {
    struct node* root = NULL;
    
    // 插入节点
    root = insert(root, 50);
    root = insert(root, 30);
    root = insert(root, 20);
    root = insert(root, 40);
    root = insert(root, 70);
    root = insert(root, 60);
    root = insert(root, 80);
    
    // 中序遍历
    printf("中序遍历: ");
    inOrderTraversal(root);
    
    return 0;
}

典型使用场景

  1. 学习算法:通过阅读源码理解算法原理
  2. 算法验证:使用测试用例验证算法正确性
  3. 代码重用:在项目中直接使用经过验证的算法实现
  4. 面试准备:复习数据结构和算法知识

API概览

项目中的主要数据结构API包括:

  • 栈操作:push、pop、peek、isEmpty、size
  • 队列操作:enqueue、dequeue、isEmpty
  • 链表操作:insert、delete、search、traverse
  • 树操作:insert、delete、search、traversal
  • 图操作:BFS、DFS、shortest path、minimum spanning tree
  • 哈希表操作:add、get、remove、contains

核心代码

A-law编码算法核心实现

代码语言:c
复制
/**
 * @brief 16bit pcm to 8bit alaw
 * @param out unsigned 8bit alaw array
 * @param in  signed 16bit pcm array
 * @param len length of pcm array
 * @returns void
 */
void encode(uint8_t *out, int16_t *in, size_t len)
{
    uint8_t alaw = 0;
    int16_t pcm = 0;
    int32_t sign = 0;
    int32_t abcd = 0;
    int32_t eee = 0;
    int32_t mask = 0;
    
    for (size_t i = 0; i < len; i++)
    {
        pcm = *in++;
        eee = 7;
        mask = 0x4000;  // 0x4000: '0b0100 0000 0000 0000'
        
        // 获取符号位
        sign = (pcm & 0x8000) >> 8;
        
        // 将负数转换为正数进行处理
        pcm = pcm < 0 ? (~pcm >> 4) : pcm;
        
        // 查找量化级别
        while ((mask & pcm) == 0 && eee > 0)
        {
            mask >>= 1;
            eee--;
        }
        
        // 提取abcd位
        abcd = (pcm >> (eee ? (eee + 3) : 4)) & 0x0f;
        alaw = (uint8_t)(sign | eee << 4 | abcd);
        alaw ^= 0xd5;
        *out++ = alaw;
    }
}

仿射密码核心实现

代码语言:c
复制
/**
 * @brief finds the value x such that (a * x) % m = 1
 * @param a number we are finding the inverse for
 * @param m the modulus the inversion is based on
 * @returns the modular multiplicative inverse of `a` mod `m`
 */
int modular_multiplicative_inverse(unsigned int a, unsigned int m)
{
    int x[2] = {1, 0};
    div_t div_result;

    if (m == 0) {
        return 0;
    }
    a %= m;
    if (a == 0) {
        return 0;
    }

    div_result.rem = a;

    while (div_result.rem > 0)
    {
        div_result = div(m, a);
        m = a;
        a = div_result.rem;

        // 计算当前迭代的x值
        int next = x[1] - (x[0] * div_result.quot);
        x[1] = x[0];
        x[0] = next;
    }

    return x[1];
}

/**
 * @brief Encrypts character string `s` with key
 * @param s string to be encrypted
 * @param key affine key used for encryption
 * @returns void
 */
void affine_encrypt(char *s, affine_key_t key)
{
    for (int i = 0; s[i] != '\0'; i++)
    {
        int c = (int)s[i] - Z95_CONVERSION_CONSTANT;
        c *= key.a;
        c += key.b;
        c %= ALPHABET_SIZE;
        s[i] = (char)(c + Z95_CONVERSION_CONSTANT);
    }
}

二叉树插入操作核心实现

代码语言:c
复制
/**
 * @brief Insertion procedure, which inserts the input key in a new node in the tree
 * @param root pointer to parent node
 * @param data value to store in the new node
 * @returns pointer to parent node
 */
node *insert(node *root, int data)
{
    // 如果子树根节点为空,在此处插入键值
    if (root == NULL)
    {
        root = newNode(data);
    }
    else if (data > root->data)
    {
        // 如果不为空且输入键值大于根键值,插入右叶子
        root->right = insert(root->right, data);
    }
    else if (data < root->data)
    {
        // 如果不为空且输入键值小于根键值,插入左叶子
        root->left = insert(root->left, data);
    }
    // 返回修改后的树
    return root;
}

/**
 * Node, the basic data structure in the tree
 */
typedef struct node
{
    struct node *left;  // 左子节点
    struct node *right; // 右子节点
    int data;           // 节点数据
} node;

/**
 * The node constructor
 * @param data data to store in a new node
 * @returns new node with the provided data
 */
node *newNode(int data)
{
    node *tmp = (node *)malloc(sizeof(node));
    tmp->data = data;
    tmp->left = NULL;
    tmp->right = NULL;
    return tmp;
}

动态数组核心实现

代码语言:c
复制
/**
 * @brief Vector structure definition
 */
typedef struct {
    int len;           // 向量长度
    int current;       // 当前项索引
    int* contents;     // 内部数组指针
} Vector;

/**
 * @brief Initialize vector with size 1
 * @param vec pointer to Vector struct
 * @param val initial value
 */
void init(Vector* vec, int val) {
    vec->contents = (int*)malloc(sizeof(int));
    vec->contents[0] = val;
    vec->current = 0;
    vec->len = 1;
}

/**
 * @brief Push value to end of vector
 * @param vec pointer to Vector struct
 * @param val value to be pushed
 */
void push(Vector* vec, int val) {
    vec->contents = realloc(vec->contents, (sizeof(int) * (vec->len + 1)));
    vec->contents[vec->len] = val;
    vec->len++;
}

/**
 * @brief Get item at specified index
 * @param vec pointer to Vector struct
 * @param index index to get value from
 * @returns value at index or -1 if out of bounds
 */
int get(Vector* vec, int index) {
    if(index < vec->len) {
        return vec->contents[index];
    }
    return -1;
}

迪杰斯特拉算法核心实现

代码语言:c
复制
/**
 * @brief The main function that finds the shortest path from given source
 * to all other vertices using Dijkstra's Algorithm.
 */
void Dijkstra(struct Graph *graph, int src)
{
    int V = graph->vertexNum;
    int mdist[V];  // 存储到顶点的更新距离
    int vset[V];   // vset[i]为true表示顶点i包含在最短路径树中

    // 初始化mdist和vset,设置源点距离为0
    for (int i = 0; i < V; i++) {
        mdist[i] = INT_MAX;
        vset[i] = 0;
    }

    mdist[src] = 0;

    // 迭代查找最短路径
    for (int count = 0; count < V - 1; count++)
    {
        int u = minDistance(mdist, vset, V);
        vset[u] = 1;

        for (int v = 0; v < V; v++)
        {
            if (!vset[v] && graph->edges[u][v] != INT_MAX &&
                mdist[u] + graph->edges[u][v] < mdist[v])
                mdist[v] = mdist[u] + graph->edges[u][v];
        }
    }

    print(mdist, V);
}

这些核心代码展示了项目中算法实现的质量和风格,每个函数都有详细的注释说明其功能、参数和返回值,便于理解和学习。FINISHED

0UokHtaIOxPRhj1lPtp9Tg==

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 项目标题与描述
  • 功能特性
    • 音频处理
    • 加密算法
    • 客户端-服务器通信
    • 进制转换
    • 数据结构
    • 图算法
    • 表达式转换
  • 安装指南
    • 系统要求
    • 编译步骤
    • 平台注意事项
  • 使用说明
    • 基础使用示例
      • A-law音频编码解码
      • 仿射密码
      • 二叉树操作
    • 典型使用场景
    • API概览
  • 核心代码
    • A-law编码算法核心实现
    • 仿射密码核心实现
    • 二叉树插入操作核心实现
    • 动态数组核心实现
    • 迪杰斯特拉算法核心实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档