MET CS 341 Homework 4A
Dr. Maslanka
Students in ABC College are enrolling in courses. Each student may enroll in up to four courses. The available courses are French, History, Mathematics, Biology, Literature, German, Italian. Physics, Chemistry, Drama and Education. The maximum number of courses in which each student may enroll is four. However, a student may enroll in 1, 2 or 3 courses.
For example, Anna wants to enroll in French, Literature, Drama and Education; Brian wants to enroll in Mathematics and Physics; Charles wants to enroll in Biology, German and Chemistry and Doris wants to enroll in Italian. Please write your program so that the student names and courses must be entered at the keyboard. You may construct other students and courses which follow the rule of 1 to 4 classes per student to serve as data for your program. The data must be entered manually at the user’s keyboard.
Please set up a linked list which accepts the first name of each student. Then for each student the program accepts the list of courses in which the student wishes to enroll. Also, the program sets up a linked list of courses for each student.
The program should use C++ class to set up the procedure for entering the students, and another C++ class to manage the courses in which the student is enrolled. In addition, the program needs to produce a list of the first names of the students. Also, for each student individually the program should produce a list of the courses in which the student has enrolled.
留学生作业
#include <iostream> #include <string> using namespace std; class List { //节点结构 struct Node { string name; Node* next; List* sub_list; Node(const string& n) :name(n), next(NULL), sub_list(new List) {} }; Node* head;//头节点 //清理链表函数 void clear() { Node* p = head; //从头节点开始循环删除 while (p) { Node* q = p->next; delete p; p = q; } } //查找数据d的上一个节点位置的函数 public: List() { head = nullptr; } ~List() { clear(); } //插入函数 void insert(const string& n, const string& c) { Node* f = head; //查重 while (f != nullptr ) { if (f->name == n) { break; } f = f->next; } //没找到 if (f == nullptr) { Node* p = new Node(n); Node* tmp = head; head = p; p->next = tmp; } if (c != "") { head->sub_list->insert(c, ""); } } void print() { Node* h1 = head; while (h1) { cout << "student: " << h1->name << endl;; Node* h2 = h1->sub_list->head; while (h2) { cout << " " << h2->name; h2 = h2->next; } cout << endl; h1 = h1->next; } } }; int main() { int a; List l; while (1) { std::cout << "please choose" << endl; std::cout << " 0:insert a data" << endl; std::cout << " 1:print now data" << endl; std::cout << " 2: to exit" << endl; cin >> a; if (a == 2) { break; } else if (a == 0) { cout << "please enter name and cource\r\n"; string s1, s2; cin >> s1 >> s2; l.insert(s1 ,s2); } else if (a == 1) { l.print(); } } return 0; }