addStudent 函数和 mainMenu 函数是重要的两个。
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
string major;
Student *p_next;
};
Student *addStudent(Student *p_students)
{
Student *p_new_student = new Student;
cout << "Student name: \n";
cin >> p_new_student->name;
cout << p_new_student->name << "'s major: \n";
cin >> p_new_student->major;
Student *p_place_holder = new Student;
Student *p_all_students = new Student;
p_all_students = p_students;
p_place_holder = NULL;
if (p_students == NULL) // Adds the first element to the linked list which was initialized to NULL
{
p_new_student->p_next = p_students;
delete p_place_holder;
delete p_all_students;
return p_new_student;
}
else // Adds elements beyond the first element to the linked list
{
while (p_all_students != NULL)
{
if (p_new_student->name.compare(p_all_students->name) <= 0)
{
if (p_place_holder == NULL) /* if p_new_student->name is before
p_all_students->name and p_all_students is still the first element in the list*/
{
p_new_student->p_next = p_all_students;
p_all_students = p_new_student;
delete p_place_holder;
return p_all_students;
}
else
{
p_new_student->p_next = p_all_students;
p_place_holder->p_next = p_new_student;
return p_students;
}
}
else if (p_new_student->name.compare(p_all_students->name) > 0)
{
p_place_holder = p_all_students;
p_all_students = p_all_students->p_next;
}
}
}
}
void mainMenu(Student *p_students)
{
int response = 0;
cout << "1. Add Student\n";
cout << "2. View Students\n";
cin >> response;
if (response == 1) // calls addStudent 4 times and then mainMenu
{
p_students = addStudent(p_students);
p_students = addStudent(p_students);
p_students = addStudent(p_students);
p_students = addStudent(p_students);
mainMenu(p_students);
}
else if (response == 2) // lists the students and their majors and then exits
{
while (p_students != NULL)
{
cout << p_students->name << '\n';
cout << p_students->major << "\n\n";
p_students = p_students->p_next;
}
}
delete p_students; // hopefully deletes all allocated memory
}
int main()
{
Student *p_students = new Student;
p_students = NULL;
mainMenu(p_students);
}
基本上想知道是否“删除p_students;” 在 mainMenu 函数中将正确删除所有分配的内存,以便程序不会泄漏内存。任何帮助表示赞赏,非常感谢。