广义表(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);

}
相关推荐
笑鸿的学习笔记4 分钟前
leetcode-442.数组中重复的数据
数据结构·算法·leetcode
醉城夜风~20 分钟前
[数据结构]单值二叉树
数据结构·算法
刃神太酷啦28 分钟前
C++(蓝桥杯常考点)
数据结构·c++·蓝桥杯c++组
星空露珠35 分钟前
迷你世界脚本世界接口:World
数据结构·游戏·lua
星空露珠43 分钟前
迷你世界脚本方块接口:Block
数据结构·游戏·lua
柃歌1 小时前
【UCB CS 61B SP24】Lecture 19 & 20: Hashing & Hashing II 学习笔记
java·数据结构·笔记·学习·算法
HBryce241 小时前
《数据结构》
java·数据结构
Archer1942 小时前
C语言——结构体、联合体/共用体、枚举类型、typedef关键字
c语言·开发语言
小呀小萝卜儿2 小时前
2025-02-28 学习记录--C/C++-PTA 7-34 通讯录的录入与显示
c语言·学习
Mr.pyZhang2 小时前
安卓基础组件Looper - 03 java层面的剖析
android·java·数据结构·epoll