当我创建一个链接列表来复制一个费用管理器时,我被困在寻找费用最大的那一天。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");
}