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

}
相关推荐
whoarethenext1 小时前
c/c++的opencv高斯模糊
c语言·c++·图像处理·opencv·图像预处理·高斯模糊
Felven2 小时前
E. Scuza
数据结构·c++·算法
学习使我变快乐5 小时前
C++:无序容器
数据结构·c++·算法
2301_794461576 小时前
力扣-将x减到0的最小操作数
数据结构·算法·leetcode
whoarethenext7 小时前
C/C++的OpenCV 进行轮廓提取
c语言·c++·opencv·轮廓提取
星沁城7 小时前
108. 将有序数组转换为二叉搜索树
java·数据结构·leetcode
蚊子爱喝水7 小时前
Redis 8.0 新增数据结构深度解析:从核心功能到生态重构
数据结构·redis·重构
与己斗其乐无穷7 小时前
数据结构(6)线性表-队列
数据结构·学习
阿方.9188 小时前
《C 语言内存函数超详细讲解:从 memcpy 到 memcmp 的原理与实战》
c语言·开发语言·c++
会开花的二叉树9 小时前
哈希表的实现(上)
数据结构·散列表