用C语言实现的广义表的建立、查找、输出、取表头
时间: 2023-07-10 22:16:02 浏览: 71
好的,我了解了您的问题。下面是用C语言实现广义表建立、查找、输出、取表头的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100 //定义广义表中元素的最大长度
typedef struct GLNode{
int tag; //0表示原子,1表示子表
union {
char data[MAXSIZE]; //原子结点的值
struct GLNode *sublist; //子表的指针
}atom;
struct GLNode *next; //指向下一个广义表结点的指针
}GLNode, *GList;
//建立广义表
GList createGList(char *s) {
GList p, t, h = NULL;
int k, len;
len = strlen(s);
for (int i = 0; i < len; ) {
p = (GList)malloc(sizeof(GLNode));
if (!h) { //第一个结点
h = p;
t = h;
} else {
t->next = p;
t = p;
}
if (s[i] == '(') {
p->tag = 1; //子表结点
int j = i + 1, cnt = 1;
while (cnt) {
j++;
if (s[j] == '(') cnt++;
else if (s[j] == ')') cnt--;
}
char *sub_s = (char *)malloc(sizeof(char) * (j - i - 1));
strncpy(sub_s, s + i + 1, j - i - 1);
sub_s[j - i - 1] = '\0';
p->atom.sublist = createGList(sub_s); //递归创建子表
i = j + 1;
} else {
p->tag = 0; //原子结点
k = 0;
while (s[i] != '(' && s[i] != ')' && s[i] != ',' && i < len) {
p->atom.data[k++] = s[i++];
}
p->atom.data[k] = '\0';
}
p->next = NULL;
}
return h;
}
//查找广义表
GList searchGList(GList L, char *x) {
GList p;
if (!L) return NULL;
if (L->tag == 0) { //原子结点
if (strcmp(L->atom.data, x) == 0) return L;
else return NULL;
} else { //子表结点
p = searchGList(L->atom.sublist, x);
if (p) return p;
else return searchGList(L->next, x);
}
}
//输出广义表
void printGList(GList L) {
if (!L) return;
if (L->tag == 0) printf("%s", L->atom.data);
else {
printf("(");
printGList(L->atom.sublist);
printf(")");
}
if (L->next) {
printf(",");
printGList(L->next);
}
}
//取表头
GList getHead(GList L) {
if (!L) return NULL;
if (L->tag == 0) return NULL; //原子结点没有表头
else return L->atom.sublist;
}
int main() {
char s[MAXSIZE];
printf("请输入广义表:");
scanf("%s", s);
GList L = createGList(s);
printf("广义表为:");
printGList(L);
printf("\n请输入要查找的元素:");
scanf("%s", s);
GList p = searchGList(L, s);
if (!p) printf("未找到元素 %s\n", s);
else printf("找到元素 %s\n", s);
GList head = getHead(L);
if (head) {
printf("表头为:");
printGList(head);
printf("\n");
} else {
printf("广义表为原子结点,无法取表头\n");
}
return 0;
}
```
示例输入:
```
(1,(2,3),4)
2
```
示例输出:
```
请输入广义表:(1,(2,3),4)
广义表为:(1,(2,3),4)
请输入要查找的元素:2
找到元素 2
表头为:2
```