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

}
相关推荐
顾安r2 小时前
11.8 脚本网页 星际逃生
c语言·前端·javascript·flask
LaoZhangGong1233 小时前
STM32 F103外部晶振8MHz改为12MHz,如何配置?
c语言·stm32·单片机·嵌入式硬件·晶振
WBluuue5 小时前
数据结构与算法:树上倍增与LCA
数据结构·c++·算法
lkbhua莱克瓦245 小时前
Java基础——集合进阶用到的数据结构知识点1
java·数据结构·笔记·github
杨福瑞6 小时前
数据结构:单链表(2)
c语言·开发语言·数据结构
王璐WL7 小时前
【数据结构】单链表及单链表的实现
数据结构
GilgameshJSS7 小时前
STM32H743-ARM例程38-UART-IAP
c语言·arm开发·stm32·单片机·嵌入式硬件
z187461030037 小时前
list(带头双向循环链表)
数据结构·c++·链表
T.Ree.8 小时前
cpp_list
开发语言·数据结构·c++·list
apocelipes9 小时前
POSIX兼容系统上read和write系统调用的行为总结
linux·c语言·c++·python·golang·linux编程