广义表(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 小时前
是什么意思c语言
c语言·编程语言·底层开发·面向过程·系统软件
Sam_Deep_Thinking5 小时前
学数据结构到底有什么用
数据结构
handler016 小时前
拒绝权限报错!三分钟掌握 Linux 权限管理
linux·c语言·c++·笔记·学习
代码中介商8 小时前
C语言数据存储深度解析:从原码反码补码到浮点数存储
c语言·开发语言·内存
py有趣8 小时前
力扣热门100题之和为K的子数组
数据结构·算法·leetcode
hipolymers9 小时前
C语言怎么样?难学吗?
c语言·数据结构·学习·算法·编程
CS创新实验室9 小时前
从“跑得动”到“跑得稳”:深度剖析数据结构究竟是理论点缀还是核心战力?
数据结构
jllllyuz10 小时前
MATLAB 蒙特卡洛排队等待模拟程序
数据结构·matlab
自我意识的多元宇宙10 小时前
树、森林——树、森林与二叉树的转换(森林转换为二叉树)
数据结构
海清河晏11110 小时前
数据结构 | 双循环链表
数据结构·链表