Hi everyone. I am new to this forum and would appreciate if anyone is ready to offer me some help on this one!
The code works, but crashes when its about to print the List thats attached to each node of the tree, if you could help me that would be great!
(i haven't yet made one function, I would if this problem is solved first)
Thank you. =]
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct stackish{
char name[25];
struct stackish* next;
};
struct tree{
float gpa;
struct tree* left;
struct tree* right;
struct stackish* next;
};
struct tree* initialise(struct tree* x)
{
x=(struct tree*)malloc(sizeof(struct tree));
x->next=NULL;
x->left=x->right=NULL;
x->gpa=2;
return x;
}
void printlist(struct stackish* p)
{
p=p->next;
while(p!=NULL)
{
puts(p->name);
p=p->next;
}
}
struct tree* entering(char c[], float a, struct tree* b)
{
if(b==NULL)
{
b=(struct tree*)malloc(sizeof(struct tree));
b->gpa=a;
struct stackish* nametemp=(struct stackish*)malloc(sizeof(struct stackish));
strcpy(nametemp->name,c);
nametemp->next=b->next;
b->next=nametemp;
b->left=b->right=NULL;
}
else if(a==b->gpa)
{
struct stackish* nametemp=(struct stackish*)malloc(sizeof(struct stackish));
strcpy(nametemp->name,c);
nametemp->next=b->next;
b->next=nametemp;
}
else if(a>b->gpa)
{
b->right=entering(c,a,b->right);
}
else if(a<b->gpa)
{
b->left=entering(c,a,b->left);
}
return b;
}
struct tree* gpafind(float a, struct tree * q)
{
if(q==NULL)
{
printf("No Record please");
}
if(a>q->gpa)
{
q->right=gpafind(a,q->right);
}
else if(a<q->gpa)
{
q->left=gpafind(a,q->left);
}
else
{
printf("GPA: %.2f\n",q->gpa);
printlist(q->next);
}
return q;
}
int main()
{
struct tree* root=initialise(root);
struct tree* she=initialise(she);
int j;
char name[25];
float gpa,y;
while(j!=0)
{
printf(" \tPress 1 to enter name and GPA of that person\n\tPress 2 to print GPA-wise with name(s)\n\tPress 3 to print Name(s) wise with gpa\n\t Press 0 to exit\n");
scanf("%d",&j);
switch(j)
{
case 1:
printf("Enter Name\n");
gets(name);
gets(name);
printf("Enter GPA (GPA<4, hence take care not to enter higher it will not be recorded)\n");
scanf("%f",&gpa);
if(gpa>4)
printf("Invalid Gpa");
else
entering(name,gpa,root);
printf("\n\n");
continue;
case 0:
break;
case 2:
printf("Enter gpa to search\n");
scanf("%f",&y);
gpafind(y,root);
continue;
case 3:
//namefind();
default:
printf("Invalid entry\n\n");
break;
}
}
return 0;
}