Linked list
#include <iostream>
using namespace std;
class Node {
public:
string name;
string surName;
int age;
string gender;
Node* next;
};
void Insert(Node** head, Node* newNode)
{
Node* currentNode;
if (*head == NULL|| (*head)->age >= newNode->age) {
newNode->next = *head;
*head = newNode;
}
else {
currentNode = *head;
while (currentNode->next != NULL && currentNode->next->age< newNode->age) {
currentNode = currentNode->next;
}
newNode->next = currentNode->next;
currentNode->next = newNode;
}
}
Node* new_node(string name,string surName, int age, string gender)
{
Node* newNode = new Node();
newNode->name = name;
newNode->surName = surName;
newNode->age = age;
newNode->gender = gender;
newNode->next = NULL;
return newNode;
}
void printList(Node* head)
{
Node* temp = head;
while (temp != NULL) {
cout << temp->name << " "<<temp->surName<<" "<<temp->age<<" "<<temp->gender<<endl;
temp = temp->next;
}
}
void deleteNode(Node** head_ref, int key)
{
Node* temp = *head_ref;
Node* prev = NULL;
if (temp != NULL && temp->age == key)
{
*head_ref = temp->next;
delete temp;
return;
}
else
{
while (temp != NULL && temp->age != key)
{
prev = temp;
temp = temp->next;
}
if (temp == NULL)
return;
prev->next = temp->next;
delete temp;
}
}
int main()
{
Node* head = NULL;
Node* node = new_node("Donald", "Brown", 67, "M" );
Insert(&head, node);
node = new_node("Jason", "Travis", 90, "F");
Insert(&head, node);
node = new_node("Max", "Black", 27, "M");
Insert(&head, node);
node = new_node("Bobi", "Frank", 17, "F");
Insert(&head, node);
cout << "The list is sorted by gender in ascending order\n";
printList(head);
cout<<"After deleting a person who age is 17 the list becomes \n";
deleteNode(&head, 17);
printList(head);
cout << "When a person whose is 20 is inserted the linked list becomes\n";
node = new_node("Victoria", "Riberry", 20, "M");
Insert(&head, node);
printList(head);
return 0;
}