广义表(C语言代码链式存储结构)

cs 复制代码
typedef enum
{
	ATOM,LIST
}Nodetype;//枚举类型
typedef struct GLnode
{
	Nodetype tag;//原子 或者 子表
	union {
		char atom;//字母
		struct
		{
			struct GLnode* head;
			struct GLndoe* tail;
		};
	};
}GLnode;
//创建原子结点
GLnode* createAtom(char data)
{
	GLnode* newnode = (GLnode*)malloc(sizeof(GLnode));
	if (newnode == NULL)
	{
		perror("error");
		exit(1);
	}
	newnode->tag = ATOM;
	newnode->atom = data;
	return newnode;
}
//创建子表结点
GLnode* createList(GLnode* head, GLnode* tail)
{
	GLnode* newnode = (GLnode*)malloc(sizeof(GLnode));
	if (newnode == NULL)
	{
		perror("error");
		exit(1);
	}
	newnode->tag = LIST;
	newnode->head = head;
	newnode->tail = tail;
	return newnode;
}
//打印广义表
void printNode(GLnode* node)
{
	if(node == NULL)
	{
		printf("()");
	}
	if (node->tag == ATOM)
	{
		printf("%c", node->atom);
	}
	else
	{
		printf("(");
		GLnode* pcur = node;
		while (pcur)
		{
			printNode(pcur->head);
			if (pcur->tail != NULL)
			{
				printf(",");
			}
			pcur = pcur->tail;
		}
		printf(")");
	}
}
int main()
{
	GLnode* atomA = createAtom('a');
	GLnode* atomB = createAtom('b');
	GLnode* atomC = createAtom('c');
	GLnode* atomD = createAtom('d');

	GLnode* suiblist = createList(atomA, createList(atomB, NULL));
	GLnode* list = createList(atomC, createList(suiblist,createList(atomD,NULL)));

	printNode(list);
	printf("\n");
	printNode(suiblist);

}
相关推荐
Miraitowa_cheems5 小时前
LeetCode算法日记 - Day 73: 最小路径和、地下城游戏
数据结构·算法·leetcode·职场和发展·深度优先·动态规划·推荐算法
野蛮人6号5 小时前
力扣热题100道之560和位K的子数组
数据结构·算法·leetcode
Kratzdisteln7 小时前
【C语言】Dev-C++如何编译C语言程序?从安装到运行一步到位
c语言·c++
小白不想白a7 小时前
每日手撕算法--哈希映射/链表存储数求和
数据结构·算法
Doro再努力8 小时前
数据结构04:力扣顺序表3道例题解题思路与代码实现
c语言·数据结构
疯狂吧小飞牛8 小时前
Lua C API 中的注册表介绍
java·c语言·lua
HY小海8 小时前
【C++】AVL树实现
开发语言·数据结构·c++
花月C8 小时前
高效查找数据的数据结构—MySQL 索引
数据结构·数据库·mysql
仰泳的熊猫8 小时前
LeetCode:701. 二叉搜索树中的插入操作
数据结构·c++·算法·leetcode
疯狂吧小飞牛11 小时前
Lua C API 中一段LUA建表过程解释
c语言·junit·lua