Suppose you are given a list of students registered in a course and you are required to implement an Linked List of student. Each student in the list has name, regNo and cGpa. You task is to implement following function related to Linked List.
insertStudent() : This function, when called will prompt user to enter his/her choice of insertion. The options are
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int regNo;
float cGpa;
};
struct ListNode
{
Student data;
ListNode* next = nullptr;
};
void InsertFront(ListNode*& head, ListNode*& newStudent)
{
newStudent->next = head;
head = newStudent;
}
void InsertBack(ListNode*& head, ListNode* newStudent)
{
// in case head is null
if (!head)
{
head = newStudent;
return;
}
ListNode* node = head;
while (node->next)
{
node = node->next;
}
node->next = newStudent;
}
void InsertBefore(ListNode*& head, ListNode*& newStudent, const string& name)
{
//in case head is null or head node has needed name
if (!head || head->data.name == name)
{
InsertFront(head, newStudent);
return;
}
ListNode* node = head;
while (node && node->next)
{
const auto& data = node->next->data;
if (data.name == name)
{
newStudent->next = node->next;
node->next = newStudent;
break;
}
node = node->next;
}
// in case there is no such name, we add to the back
if (node->next == nullptr)
node->next = newStudent;
}
void PrintList(ListNode* head)
{
while (head)
{
cout << "Student's name: " << head->data.name << endl;
head = head->next;
}
cout << endl;
}
void CreateStudent(ListNode*& studentNode)
{
string name;
int regNo;
float cGpa;
cout << "Please, input name, regNo and cGpa of the student you want to insert\n";
cin >> studentNode->data.name >> studentNode->data.regNo >> studentNode->data.cGpa;
}
void InsertStudent(ListNode*& head)
{
int choice;
while(true)
{
cout << "Please, enter you choice:\n";
cin >> choice;
if (!choice) return;
ListNode* studentNode = new ListNode;
CreateStudent(studentNode);
if (choice == 1)
InsertFront(head, studentNode);
else if (choice == 2)
InsertBack(head, studentNode);
else if (choice == 3)
{
string name;
cout << "Enter name of the student, you want to insert new student before:\n";
cin >> name;
InsertBefore(head, studentNode, name);
}
cout << "List is now: \n";
PrintList(head);
}
}
int main()
{
ListNode* head = nullptr;
InsertStudent(head);
// delete list
while (head)
{
ListNode* node = head;
head = head->next;
delete node;
}
}