#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<string.h>
struct node{
char *name;
struct node *lchild;
struct node *rchild;
}*root;
void find(char *str,struct node **par,struct node **loc)
{
struct node *ptr,*ptrsave;
if(root==NULL)
{
*loc=NULL;
*par=NULL;
return;
}
if(!(strcmp(str,root->name)))
{
*loc=root;
*par=NULL;
return;
}
if(strcmp(str,root->name)<0)
ptr=root->lchild;
else
ptr=root->rchild;
ptrsave=root;
while(ptr!=NULL)
{
if(!(strcmp(str,ptr->name)))
{
*loc=ptr;
*par=ptrsave;
return;
}
ptrsave=ptr;
if(strcmp(str,ptr->name)<0)
ptr=ptr->lchild;
else
ptr=ptr->rchild;
}
*loc=NULL;
*par=ptrsave;
}
void insert(char *str)
{
struct node *parent,*location,*temp;
find(str,&parent,&location);
if(location!=NULL)
{
printf("Name already present\n");
return;
}
temp=(struct node*)malloc(sizeof(struct node));
temp->name=str;
temp->lchild=NULL;
temp->rchild=NULL;
if(parent==NULL)
root=temp;
else
if(strcmp(str,parent->name)<0)
parent->lchild=temp;
else
parent->rchild=temp;
}
void displayin(struct node *ptr)
{
if(root==NULL)
{
printf("Tree is empty");
return;
}
if(ptr!=NULL)
{
displayin(ptr->lchild);
printf("%s -> ",ptr->name);
displayin(ptr->rchild);
}
}
int main()
{
root=NULL;
char str[20];
while(1)
{
printf("Enter name: ");
fflush(stdin);
gets(str);
insert(str);
printf("Wants to insert more item: ");
if(getchar()=='y')
insert(str);
else
break;
}
displayin(root);
getch();
getchar();
return 0;
}
If i run this piece of code with following input
rakesh rajesh bimal
then,it is displaying the output as "bimal->" which is wrong. I don't know where the logic is going wrong. I crosschecked but not able to find mistake. Can somebody take a look on this.
One of the issue:
In your insert()
function you are doing
temp=(struct node*)malloc(sizeof(struct node));
temp->name=str; //this is not correct,
//do
temp=malloc(sizeof(struct node)); // no type cast for malloc
temp->name = strdup(str); //allocate memory too
//also check you NULL and free the allocated memory.
Your are just setting the pointer location in the node you created for string to store, but it points to str
array from main()
. So all nodes will point to same location, which will have last value entered. In your case its "bimal"
.
Your find function is in any case quite obscure. This is the improved version.
void find(char *str,struct node **par,struct node **loc)
{
*par = NULL;
*loc = NULL;
struct node *ptr,*ptrsave;
if(root==NULL) return;
if(!(strcmp(str,root->name)))
{
*loc=root;
return;
}
ptrsave = NULL;
ptr = root;
while(ptr!=NULL) {
if(!(strcmp(str,ptr->name))) break;
ptrsave = ptr;
if(strcmp(str,ptr->name)<0)
ptr=ptr->lchild;
else
ptr=ptr->rchild;
}
*loc=ptr;
*par=ptrsave;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.