Когда я создавал связанный список для репликации менеджера расходов, я застрял с поиском дня с наибольшими расходами. Мне каким-то образом удалось найти максимальное значение total
через обход, но я не смог распечатать day
, связанный с ним. Пожалуйста, помогите.
Код моей структуры:
struct node{
int day;
int movies;
int groceries;
int travel;
int total;
struct node* left;
struct node* right;
};
void find_max()
{
struct node *new1 = start;
int max, c;
if(start == NULL) {
printf("List is empty\n");
return;
}
else {
max = start->total;
while(new1 != NULL) {
if(new1->total > max)
{
max = new1->total;
}
new1 = new1->right;
}
}
printf("The maximum spending was: %d",max);
}
Здесь, когда я пытаюсь напечатать new1->day
(я не уверен, как это называется. Это ветвь?), он показывает мне значение мусора или перестает работать.
Как правильно отобразить его?
Редактировать (код):
#include<stdio.h>
#include<stdlib.h>
struct node{
int day;
int movies;
int groceries;
int travel;
int total;
struct node* left;
struct node* right;
};
void maximumNode();
//Main goes here, where I choose the option using switch case. Say the example is case 3
case 3:
{
maximumNode();
break;
}
//End of main
void maximumNode() {
struct node *new1 = start;
struct node *max;
if(start == NULL) {
printf("List is empty\n");
return;
}
else {
max->total = start->total;
while(new1 != NULL) {
if(new1->total > max->total)
{
max->total = new1->total;
}
new1 = new1->right;
}
}
printf("The maximum spending was: %d and the day was: %d\n\n",max->total, max->day);
}
Здесь, как только я наберу слово 3 после добавления его в список,программа даже не запускается. (Он запустился, когда я взял max
в качестве значения int).
Редактировать 2: Я просто перезапустил свой код и, по-видимому, допустил ошибки даже во вставке. Прошу прощения за трату времени всех и благодарю всех за поддержку.
Мой код для вставки, на всякий случай:
void Insert(int a, int b, int c, int d)
{
struct node *temp,*t;
int total1=b+c+d;
temp=(struct node*)malloc(sizeof(struct node));
if(start==NULL)
{
start=temp;printf("%d", total1);
start->day=a;
start->movies=b;
start->groceries=c;
start->travel=d;
start->total=total1;
start->left=NULL;
start->right=NULL;
}
else
{
temp=start;
while(temp->right!=NULL)
{
temp=temp->right;
}
t=(struct node*)malloc(sizeof(struct node));
start->day=a;
start->movies=b;
start->groceries=c;
start->travel=d;
start->total=total1;
t->right=NULL;
t->left=temp;
temp->right=t;
}
printf("\n\nYour expense has been saved successfully!\n\n");
}