Question
This is a C++ linked list Question. I need to insert a college class into a linked list in alphabetical order based on the name
This is a C++ linked list Question. I need to insert a college class into a linked list in alphabetical order based on the name of the class. I have a problem with my add function. When I add three classes and try to display the classes, the output goes into an infinite loop. Also when you add a class that would go on the end of the list the add function goes into an infinite loop. I think my problem is with the section that adds the node to the end of the linked list. The get_course_number() function returns the string name of the course to be placed in alphabetical order.
Here is my node class:
#ifndef NODE_H #define NODE_H #include "course.h" class node{ public: typedef course value_type; // Universal constructor node(value_type d = value_type(), node *l = NULL) {data_field = d; link_field = l;} // Mutator functions void set_data(value_type d) {data_field = d;} void set_link(node *l) {link_field = l;} // Accessor functions value_type data() const {return data_field;} node* link() {return link_field;} const node* link() const {return link_field;} private: value_type data_field; node* link_field; }; #endif
Here is my College Class:
#include "college.h" #include #include #include #include using namespace std;
College::College(string x){ student_name = x; head_ptr = NULL; curr_ptr = NULL; prev_ptr = NULL; next_ptr = NULL; }
College::~College(){ node * prev_ptr; node * curr_ptr; prev_ptr = curr_ptr = head_ptr; while (curr_ptr != NULL){ curr_ptr = prev_ptr->link(); delete prev_ptr; prev_ptr = curr_ptr; } prev_ptr = curr_ptr = head_ptr = NULL; }
void College::add(course c){ cout<<"starting add function" << endl; prev_ptr = head_ptr; next_ptr = head_ptr; node * temp_ptr = new node(c); curr_ptr = head_ptr; if (curr_ptr == NULL) // empty list { head_ptr = temp_ptr; } else { while (curr_ptr != NULL){ if (curr_ptr->link() == NULL) // end of list { curr_ptr->set_link(temp_ptr); break; } else if ( temp_ptr->data().get_course_number() < curr_ptr->data().get_course_number() ) // insert temp { temp_ptr->set_link( curr_ptr->link() ); curr_ptr->set_link( temp_ptr ); break; } curr_ptr->set_link( curr_ptr->link() ); } } }
void College::display(ostream& cout){ curr_ptr = head_ptr; while(curr_ptr != NULL){
cout << "Class Number: " << curr_ptr->data().get_course_number() << endl; cout << "Class Grade: " << curr_ptr->data().get_number_grade() << endl; cout << "Class Hours: " << curr_ptr->data().get_hours() << endl; curr_ptr = curr_ptr->link(); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started