广义表的创建和打印c语言代码,含main函数
时间: 2023-07-25 12:19:02 浏览: 48
创建广义表的C语言代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char data;
struct node *next;
struct node *sublist;
} Node;
Node* createList(char* str, int len) {
Node* head = NULL;
Node* cur = NULL;
Node* pre = NULL;
int i = 0;
while (i < len) {
cur = (Node*)malloc(sizeof(Node));
cur->data = str[i++];
cur->next = NULL;
cur->sublist = NULL;
if (cur->data == '(') {
cur->sublist = createList(str+i, len-i);
while (str[i] != ')') i++;
}
if (head == NULL) {
head = cur;
} else {
pre->next = cur;
}
pre = cur;
}
return head;
}
void printList(Node* head) {
if (head == NULL) return;
printf("%c", head->data);
if (head->sublist != NULL) {
printf("(");
printList(head->sublist);
printf(")");
}
printList(head->next);
}
int main() {
char str[] = "(a, b, (c, d), e)";
Node* head = createList(str, sizeof(str)-1);
printList(head);
return 0;
}
```
上述代码中,我们用结构体 `Node` 表示广义表中的每个元素,其中 `data` 表示当前元素的值,`next` 表示当前元素的下一个元素,`sublist` 表示当前元素的子表。
首先,我们通过 `createList` 函数创建广义表,参数 `str` 表示广义表的字符串形式,参数 `len` 表示字符串的长度。在该函数中,我们遍历字符串,创建每个元素,如果当前元素的值是 `'('`,则说明该元素有子表,我们递归调用 `createList` 函数创建子表,并跳过子表中的元素。最后,函数返回广义表的头结点。
接下来,我们通过 `printList` 函数打印广义表。该函数首先打印当前元素的值,如果当前元素有子表,则在值后面打印 `'('`,递归调用自己打印子表,最后在子表打印完后打印 `')'`。最后,函数递归调用自己打印当前元素的下一个元素。
在 `main` 函数中,我们给出一个广义表的字符串形式,并调用 `createList` 函数创建广义表,然后调用 `printList` 函数打印广义表。