广义表-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;
}
相关推荐
sukalot7 分钟前
windows C++-使用任务和 XML HTTP 请求进行连接(一)
c++·windows
落落落sss13 分钟前
MybatisPlus
android·java·开发语言·spring·tomcat·rabbitmq·mybatis
ぃ扶摇ぅ25 分钟前
Windows系统编程(三)进程与线程二
c++·windows
简单.is.good31 分钟前
【测试】接口测试与接口自动化
开发语言·python
Yvemil71 小时前
MQ 架构设计原理与消息中间件详解(二)
开发语言·后端·ruby
程序员是干活的1 小时前
私家车开车回家过节会发生什么事情
java·开发语言·软件构建·1024程序员节
我是陈泽1 小时前
一行 Python 代码能实现什么丧心病狂的功能?圣诞树源代码
开发语言·python·程序员·编程·python教程·python学习·python教学
优雅的小武先生1 小时前
QT中的按钮控件和comboBox控件和spinBox控件无法点击的bug
开发语言·qt·bug
虽千万人 吾往矣1 小时前
golang gorm
开发语言·数据库·后端·tcp/ip·golang
创作小达人1 小时前
家政服务|基于springBoot的家政服务平台设计与实现(附项目源码+论文+数据库)
开发语言·python