gpt4 book ai didi

c++ - 将项目添加到列表问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:53:35 25 4
gpt4 key购买 nike

我正在创建一个简单的问题。我尝试将学生添加到一个列表中,然后将其分成两个列表。我创建了一个将节点添加到列表的通用方法,但它似乎运行不佳。这就是我尝试过的。我做错了什么?

int main()
{
for(int i=0;i<NR_STUDENTS;i++)
{
Student *studToAdd=new Student;
cout<<"Student #"<<i<<endl;
cout<<"Name:";
cin>>studToAdd->name;
cout<<"Grade:";
cin>>studToAdd->grade;
Add(studToAdd);
}
Split();
Print();
}

#include "students.h"

Node *allFirstNode;
Node *admitedFirstNode;
Node * rejectedFirstNode;


void AddNodeToList(Node *firstNode, Student *studToAdd)
{
Node *nodeToAdd=new Node;
nodeToAdd->student=studToAdd;
nodeToAdd->next=NULL;

if(firstNode==NULL)
{
firstNode=nodeToAdd;
}
else
{
Node *temp;
temp=firstNode;
while(temp->next != NULL)
{
temp=temp->next;
}
temp->next=nodeToAdd;
}
}
void addStudent(Student *studentToAdd)
{
AddNodeToList(allFirstNode,studentToAdd);
}

void split()
{
Node *temp=allFirstNode;
while(temp->next != NULL)
{
Student *currentStud=temp->student;
if(currentStud->grade < GR)
{
AddNodeToList(rejectedFirstNode,currentStud);
}
else
{
AddNodeToList(admitedFirstNode,currentStud);
}
}
}


void PrintList(Node *first)
{
Node *temp=first;
while(temp!=0)
{
cout<<temp->student->name<<":"<<temp->student->grade<<endl;
temp=temp->next;
}
}
void Print()
{
PrintList(admitedFirstNode);
PrintList(rejectedFirstNode);
}
#include <iostream>
#include <string>

using namespace std;

const int NR_STUDENTS=2;
const double GR=5.0;

struct Student
{
string name;
double grade;
};

struct Node
{
Student *student;
Node *next;
};

extern Node *allFirstNode;
extern Node *admitedFirstNode;
extern Node * rejectedFirstNode;

void addStudent(Student *studentToAdd);
void split();
void sort();
void print(Node *firsNode);

最佳答案

您需要通过引用调用(您不需要更改任何其他内容):

void AddNodeToList(Node* &firstNode, Student *studToAdd)

关于c++ - 将项目添加到列表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com