广义表-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;
}
相关推荐
雾岛听蓝16 小时前
深入解析内存中的整数与浮点数存储
c语言·经验分享·笔记·visualstudio
Yupureki16 小时前
从零开始的C++学习生活 9:stack_queue的入门使用和模板进阶
c语言·数据结构·c++·学习·visual studio
一念&17 小时前
每日一个C语言知识:C 数组
c语言·开发语言·算法
小年糕是糕手17 小时前
【数据结构】单链表“0”基础知识讲解 + 实战演练
c语言·开发语言·数据结构·c++·学习·算法·链表
疯狂吧小飞牛17 小时前
Lua C API 中的 lua_rawseti 与 lua_rawgeti 介绍
c语言·开发语言·lua
Tony Bai17 小时前
【Go 网络编程全解】06 UDP 数据报编程:速度、不可靠与应用层弥补
开发语言·网络·后端·golang·udp
半夏知半秋17 小时前
lua对象池管理工具剖析
服务器·开发语言·后端·学习·lua
大飞记Python17 小时前
Windows10停服!7-Zip被爆组合漏洞|附安全指南
开发语言
浪裡遊18 小时前
MUI组件库与主题系统全面指南
开发语言·前端·javascript·vue.js·react.js·前端框架·node.js
一匹电信狗18 小时前
【C++】C++风格的类型转换
服务器·开发语言·c++·leetcode·小程序·stl·visual studio