laura
laura

Reputation: 2135

Add item to list issue

I am creating a simple problem. I try to add students to one list then split it in two lists. I created a general method that adds a node to a list but it doesn't seem to function well. This is what I tried. What I am doing wrong?

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);

Upvotes: 2

Views: 288

Answers (1)

Roozbeh Zabihollahi
Roozbeh Zabihollahi

Reputation: 7347

You need to call by reference (You do not need to change anything else):

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

Upvotes: 2

Related Questions