Ive written this program yet have stumbled upon a problem. in this program, im supposed to make a linked list of students. i must then implement some basic functions. one is to add a student (which i believe is working properly) and another is to getStudent. i believe the code is written correctly, but i may be mistaken. when i try to getStudent, i have no display on the command line. is there something wrong with my code?
any help would be greatly appreciated.
thanks!
#include <iostream>
#include <string>
using namespace std;
//new class for studentnode
class studentnode
{
public:
string data;
studentnode * next;
// string to hold student name
string student;
};
//new class for studentlist
class studentlist
{
private:
studentnode * start;
public:
studentlist()
{
start = NULL;
}
// function to add a new student to list
void add(string student)
{
//create a new node
studentnode * somenode;
somenode = new studentnode;
//put student in the new node!
somenode->data = student;
//put new node at front of list!
somenode->next = start;
start = somenode;
}
//function to a specified student, if not traverse the list until found.
void getStudent (string student)
{
studentnode *firstNodePointer;
studentnode *previousNodePointer;
studentnode *head;
head=start;
if(!head)
return;
if (head->data == student)
{
firstNodePointer = head;
head = head->next;
cout << student << "is here!" << endl;
}
else
{
firstNodePointer = head;
while (firstNodePointer != NULL && firstNodePointer->data != student)
{
previousNodePointer = firstNodePointer;
firstNodePointer = firstNodePointer->next;
if (firstNodePointer)
previousNodePointer->next = firstNodePointer->next;
delete firstNodePointer;
}
}
}
//display all the items in the list
void print()
{
studentnode * current;
current = start;
//loop through all nodes, each time doing something
while(current != NULL )
{
//display the data of the current node
cout << current->data << endl;
//move current to next node
current = current->next;
}
}
};
//main program thats .
int main()
{
cout <<"This linked list should display students as they are added" << endl;
studentlist listofstudents;
listofstudents.add("Greg");
listofstudents.add("James");
listofstudents.add("Carlos");
listofstudents.add("Bryan");
listofstudents.add("Hector");
//listofstudents.print();
//displays all names on the list
listofstudents.print();
cout << "Did it work? :)" << endl;
listofstudents.getStudent("Bryan");
while(1){}
return 0;
}