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

}
相关推荐
实心儿儿12 分钟前
算法6:相交链表
数据结构·算法·链表
每天回答3个问题16 分钟前
LeetCodeHot100|链表总结
数据结构·c++·链表
badhope19 分钟前
Python、C、Java 终极对决!谁主沉浮?谁将消亡?
java·c语言·开发语言·javascript·人工智能·python·github
AC__dream31 分钟前
2024秋招-字节跳动-算法岗笔试
数据结构·算法
一叶落43836 分钟前
LeetCode 151. 反转字符串中的单词(C语言)【双指针 + 字符串处理】
c语言·数据结构·算法·leetcode
junnhwan38 分钟前
LeetCode Hot 100——栈
java·数据结构·算法·leetcode·hot 100
superior tigre43 分钟前
347 前k个高频元素
数据结构·算法·leetcode
廖圣平43 分钟前
Drogon 现代化C ++高性能框架
android·c语言·开发语言
红豆诗人1 小时前
数据结构--栈和队列详解
数据结构
计算机安禾1 小时前
【C语言程序设计】第30篇:指针与字符串
c语言·开发语言·c++·算法·visualstudio·visual studio code·visual studio