C++ algorithms [message #1856575] |
Thu, 15 December 2022 22:00 |
radiwesaf#dfdf randraidf#Wdfd Messages: 1 Registered: December 2022 |
Junior Member |
|
|
I have a job to do. I've managed to write some code, but I'm having trouble with the rest.
Is anyone able to analyze the code and help me with this?
1. Read in from the keyboard n (n - read in by the user) subsequent data about persons (name,
name, age) and create a one-way list of them in the order in which they are loaded.
2. Print the created list using the function that prints the list beginning with some
address.
3. Insert new people into the list before every second person older than the penultimate person on
leaves. Fill in the data of new people with the data loaded by the user.
4. Print the list again
5. Delete the created list using the function that deletes the list starting at some address.
6. Print the list again.
Note 1: The word "some" means a function parameter.
Note 2: When performing various operations on the list (points 2-6), assume that we do not know the number of elements
list, so be careful not to refer to the next field of an element that doesn't exist (i.e. has a
NULL address); in particular, you should check if the list is not empty (head address ==NULL) and if it has
it has enough elements (so as not to perform impossible operations).
Note 3: Please put one person in front of each person who meets the condition.
#include <iostream>
#include <string>
using namespace std;
// A structure that stores information about a person
struct Person {
string firstName;
string lastName;
int age;
Person *next;
};
// A function that prints a one-way list with a given start
void printList(Person *head) {
// Check if the list is not empty
if (head == NULL) {
cout << "Lista jest pusta" << endl;
return;
}
// Printing each list item
cout << "Lista: " << endl;
Person *curr = head;
while (curr != NULL) {
cout << curr->firstName << " " << curr->lastName << ", wiek: " << curr->age << endl;
curr = curr->next;
}
}
// A function that adds new people to the list before every second person older than the penultimate person on the list
void addPersons(Person *head) {
// Check if the list has at least 3 elements
if (head == NULL || head->next == NULL || head->next->next == NULL) {
cout << "The list is too short to perform this operation" << endl;
return;
}
// Load data of new people
cout << "Enter the data of new people (name, surname, age):" << endl;
Person *prev = head->next;
Person *curr = head->next->next;
while (curr != NULL) {
if (curr->age > prev->age) {
// Tworzenie nowej osoby
Person *newPerson = new Person();
cin >> newPerson->firstName >> newPerson->lastName >> newPerson->age;
newPerson->next = curr;
// Adding a new person to the list
prev->next = newPerson;
// Movement of pointers
prev = curr;
curr = curr->next;
} else {
prev = curr;
curr = curr->next;
if (curr != NULL) {
prev = curr;
curr = curr->next;
}
}
}
}
|
|
|
Powered by
FUDForum. Page generated in 0.06213 seconds