广义表-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;
}
相关推荐
自由随风飘14 小时前
python 题目练习1~5
开发语言·python
Bony-15 小时前
Go语言完全学习指南 - 从基础到精通------语言基础篇
服务器·开发语言·golang
ShineSpark16 小时前
Crashpad 在windows下编译和使用指南
c++·windows
fl17683116 小时前
基于python的天气预报系统设计和可视化数据分析源码+报告
开发语言·python·数据分析
ACP广源盛1392462567316 小时前
(ACP广源盛)GSV6172---MIPI/LVDS 信号转换为 Type-C/DisplayPort 1.4/HDMI 2.0 并集成嵌入式 MCU
c语言·开发语言·单片机·嵌入式硬件·音视频
不穿格子的程序员16 小时前
从零开始刷算法-栈-括号匹配
java·开发语言·
雪域迷影17 小时前
C#中通过get请求获取api.open-meteo.com网站的天气数据
开发语言·http·c#·get
yue00817 小时前
C#类继承
java·开发语言·c#
Want59517 小时前
Python汤姆猫
开发语言·python
炮院李教员17 小时前
TortoiseSVN 右键不显示的解决方法
windows