广义表-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;
}
相关推荐
倔强青铜33 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian4 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
珊瑚里的鱼4 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上4 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
xingshanchang4 小时前
Matlab的命令行窗口内容的记录-利用diary记录日志/保存命令窗口输出
开发语言·matlab
Risehuxyc4 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
AI视觉网奇4 小时前
git 访问 github
运维·开发语言·docker
不知道叫什么呀5 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc
liulilittle5 小时前
.NET ExpandoObject 技术原理解析
开发语言·网络·windows·c#·.net·net·动态编程
wan_da_ren5 小时前
JVM监控及诊断工具-GUI篇
java·开发语言·jvm·后端