【发布时间】:2018-11-01 01:56:41
【问题描述】:
我的 C 代码的重点是按字母顺序插入字符串节点。这是我的代码....
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char * word;
struct node * left;
struct node * right;
}treeNode;
treeNode * head = NULL;
void traverse (treeNode * h)
{
if(h->left == NULL){
scanf("%s ", h->word);
if(h->right != NULL){
traverse(h->right);
}
}
else{
traverse(h->left);
printf("%s ", h->word);
if(h->right != NULL){
traverse(h->right);
}
}
treeNode *newNode(char * s)
{
treeNode *insert = (treeNode*)malloc(100*sizeof(treeNode));
insert->left = NULL;
insert->right = NULL;
insert->word = s;
return insert;
}
treeNode * addNode (treeNode * h, char * s)
{
if(h == NULL){
return newNode(s);
}
else{
if (strcmp (h->word, s)> 0){
h->left = addNode(h->left,s);
}
else{
h->right = addNode(h->right,s);
}
}
return h;
}
void main()
{
printf("\nTest Animals 1");
head = insert(head, "dog");
insert(head, "horse");
insert(head, "frog");
insert(head, "fish");
insert(head, "cow");
traverse(head);
head = NULL;
printf("\nTest Food 2");
head = insert(head, "pizza");
insert(head, "sushi");
insert(head, "burger");
insert(head, "salad");
insert(head, "nuggets");
traverse(head);
head = NULL;
printf("\nTest Sports 3");
head = insert(head, "soccer");
insert(head, "basketball");
insert(head, "football");
insert(head, "tennis");
insert(head, "gymnastics");
traverse(head);
head = NULL;
}
它编译完美,完全没有错误,但我的主要方法不允许我打印出我的示例测试用例。会不会是代码本身的问题?我已经看了一遍,我看不出它有什么问题。这也是我的第一个 C 代码,如果有可能遗漏的错误,我深表歉意。
【问题讨论】:
-
欢迎来到 SO!您能解释一下为什么在遍历中使用
scanf和printf吗?你期待什么样的输出?(treeNode*)malloc(100*sizeof(treeNode))不需要演员表,100似乎是任意的。我找不到您的insert方法,并且从未使用过addNode。 -
"它编译完美,完全没有错误" 它肯定不会! bad.c:31:3:错误:此处不允许函数定义 bad.c:40:1:错误:此处不允许函数定义 bad.c:55:1:错误:此处不允许函数定义错误。 c:86:2: 错误:预期 '}'
-
您好!我在创建代码时在网上查找了很多这些方法,scanf 不应该在那里。基本上,我试图按字母顺序排列我的节点列表。
-
函数
insert未在您的代码中声明/定义。另外,分配一个节点只需要treeNode *insert = malloc(sizeof(treeNode));,不要乘以100 -
哦,我现在看到问题了,我只是不确定在我的 main 函数中调用 addNode 方法时应该使用哪些参数。还在挣扎