广义表-C语言

广义表(Generalized List)是一种扩展了线性表的数据结构,它在线性表的基础上增加了元素可以是表的特点。在广义表中,元素不仅可以是单个的数据元素,还可以是一个子表,而子表中的元素也可以是数据元素或其他的子表,这样递归定义,形成了一种层次结构

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

// 定义广义表节点结构
typedef struct GLNode {
    char data; // 可以根据需要修改为其他类型
    struct GLNode *next; // 指向下一个节点
    struct GLNode *child; // 指向子表
} GLNode, *GList;

// 创建广义表节点
GLNode *CreateGListNode(char data) {
    GLNode *node = (GLNode *)malloc(sizeof(GLNode));
    if (node) {
        node->data = data;
        node->next = NULL;
        node->child = NULL;
    }
    return node;
}

// 插入节点到广义表
void InsertGListNode(GList *list, char data) {
    GLNode *node = CreateGListNode(data);
    if (node) {
        node->next = *list;
        *list = node;
    }
}

// 插入子表到广义表
void InsertChildGListNode(GList *list, GList child) {
    GLNode *node = CreateGListNode('\0'); // 使用空字符表示子表
    if (node) {
        node->child = child;
        node->next = *list;
        *list = node;
    }
}

// 打印广义表
void PrintGList(GList list) {
    GLNode *p = list;
    while (p) {
        if (p->data != '\0') {
            printf("%c ", p->data);
        } else {
            printf("(");
            PrintGList(p->child);
            printf(") ");
        }
        p = p->next;
    }
}

// 释放广义表空间
void FreeGList(GList list) {
    GLNode *p = list;
    while (p) {
        GLNode *temp = p;
        p = p->next;
        if (temp->child) {
            FreeGList(temp->child);
        }
        free(temp);
    }
}

int main() {
    GList list = NULL;

    // 创建广义表 (a, (b, c))
    InsertGListNode(&list, 'a');
    GList child1 = NULL;
    InsertGListNode(&child1, 'b');
    InsertGListNode(&child1, 'c');
    InsertChildGListNode(&list, child1);

    // 打印广义表
    printf("广义表: ");
    PrintGList(list);
    printf("\n");

    // 释放空间
    FreeGList(list);

    return 0;
}
相关推荐
xiaozi41203 分钟前
Ruey S. Tsay《时间序列分析》Python实现笔记:综合与应用
开发语言·笔记·python·机器学习
wearegogog12312 分钟前
DEA模型MATLAB实现(CCR、BCC、超效率)
开发语言·算法·matlab
郝学胜-神的一滴21 分钟前
Linux定时器编程:深入理解setitimer函数
linux·服务器·开发语言·c++·程序人生
cici1587426 分钟前
基于反向传播算法实现手写数字识别的MATLAB实现
开发语言·算法·matlab
fushan201229 分钟前
Windows 虚拟机配置与驱动安装记录
windows·k8s·vm·kubevirt
一瞬祈望34 分钟前
【环境配置】Windows 下使用 Anaconda 创建 Python 3.8 环境 + 安装 PyTorch + CUDA(完整教程)
pytorch·windows·python
不会编程的小寒1 小时前
C and C++ 八股文
c语言·c++·青少年编程
曹牧1 小时前
Java String[] 数组的 contains
java·开发语言·windows
yong99901 小时前
LSD直线提取算法 MATLAB
开发语言·算法·matlab
一只专注api接口开发的技术猿1 小时前
构建电商数据中台:基于淘宝 API 关键词搜索接口的设计与实现
大数据·开发语言·数据库