bstsort.c结构本身正在改变值?
#include "header.h"
/*
I had to write my own string functions.
checkString = returns 1 if the strings are the same, 0 otherwise
checkGreaterString = returns 1 if arg1 comes before arg2, 0 otherwise
*/
//insert a node
int insertNode(struct NODE *root, char *compare, int cFlag)
{
// root node
//printf("root -> input : %s\n", root -> input);
//strings are the same
if(checkString(root->input, compare, cFlag))
{
//printf("same string\n");
root->isDuplicate++; // count as duplicate
//printf("root input %s and its duplicates is : %d\n", root->input, root->isDuplicate);
return 0;
}
//strings are different
else
{
int check = checkGreaterString(root->input, compare, cFlag);
//printf("check: %d\n", check);
//compare comes before root
if (check == 1)
{
// store compare at left node for root
if(root -> left == NULL){
struct NODE *tempNode = malloc(sizeof(*tempNode));
tempNode ->left = NULL;
tempNode -> right = NULL;
tempNode -> isDuplicate = 0;
tempNode -> input = compare; //give node input
root -> left = tempNode; //set left node for root
//printf("left node : %s\n", tempNode -> input);
//printf("left node duplicate : %d\n", tempNode->isDuplicate);
//printf("left nodes parent %s\n", root -> input);
return 0;
}
//left node is not empty, so insert node at that node
else
{
printf("root -> left -> input %s\n", root -> left -> input);
printf("compare : %s\n", compare);
insertNode(root -> left, compare, cFlag);
return 0;
}
}
//compare comes after root
else if(check == 0)
{
// store compare at right node for root
if(root -> right == NULL){
printf("im in the right node\n");
struct NODE *tempNode = malloc(sizeof(*tempNode));
tempNode ->left = NULL;
tempNode -> right = NULL;
tempNode -> isDuplicate = 0;
tempNode -> input = compare; //give node input
root -> right = tempNode; // set right node for root
//printf("right -> right -> input : %s\n", root -> right -> input);
//printf("root -> left -> input %s\n", root -> left -> input);
//printf("right node duplicate : %d\n", tempNode->isDuplicate);
//printf("right nodes parent %s\n", root -> input);
return 0;
}
////right node is not empty, so insert node at that node
else
{
//printf("im in the else for right node \n");
//printf("root->right->input%s\n", root -> right -> input);
insertNode(root -> right, compare, cFlag);
}
}
}
}
header.h
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
struct NODE {
struct NODE *left;
struct NODE *right;
char *input;
int isDuplicate;
};
struct NODE root;
我试图做一个二叉树,使用由用户提供的输入。输入函数在另一个文件中,但它们都正常工作。我的问题是结构,或者更精确地说,设置结构的左右节点。每次我用特定的输入设置根的左/右节点时,输入变化没有我明确地改变它。我认为问题出在我的tempNode
指针上,但我不确定问题是什么以及如何解决问题。
这里是我谈到上述问题的例子:
比方说,用户输入“的”。 “为”成为树
然后用户输入的根“吃”。 “吃”将成为根
的左子****到这里工作的。如果我打印我的根,我的根的左节点的字符串,他们会给我正确的字符串*******
现在,用户输入“测试”,“测试”并成为右子根,但现在当我打印左侧的孩子时,它也是“测试”。根字符串仍然是正确的。
任何帮助将不胜感激。谢谢!
为什么你需要两个不同的字符串比较函数'checkGreaterString'和'checkString'? – babon
@babon我的教授正在让我们做我们自己的字符串函数。 – name
但为什么两个不同的功能来做同样的工作?这两种功能如何不同? – babon