-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.cpp
101 lines (94 loc) · 2.64 KB
/
LinkedList.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* LinkedList.cpp
* Implementation of the LinkedList class.
*
* Provides detailed implementation of the LinkedList class methods, including
* adding, removing, counting, and printing nodes. This file encapsulates
* the operations associated with a singly linked list of Person objects.
*
* Justin Harris
* 05-30-2024
* COSC 350 - Advanced Algorithms and Data Structures
* Programming Assignment 5
* Columbia College of Missouri
*/
#include "LinkedList.h"
#include <iostream>
// Destructor to free the memory used by the list
LinkedList::~LinkedList() {
Node* current = head;
while (current != nullptr) {
Node* toDelete = current;
current = current->next;
delete toDelete;
}
}
// Add a new person to the list in sorted order
void LinkedList::add(const Person& person) {
Node* newNode = new Node(person);
if (head == nullptr || head->person.getFullName() >= person.getFullName()) {
newNode->next = head;
head = newNode;
}
else {
Node* current = head;
while (current->next != nullptr && current->next->person.getFullName() < person.getFullName()) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
// Remove a person from the list
bool LinkedList::remove(const std::string& fullName) {
if (head == nullptr) {
return false;
}
if (head->person.getFullName() == fullName) {
Node* toDelete = head;
head = head->next;
delete toDelete;
return true;
}
Node* current = head;
while (current->next != nullptr && current->next->person.getFullName() != fullName) {
current = current->next;
}
if (current->next == nullptr) {
return false;
}
Node* toDelete = current->next;
current->next = current->next->next;
delete toDelete;
return true;
}
// Count the number of persons in the list
int LinkedList::count() const {
int count = 0;
Node* current = head;
while (current != nullptr) {
++count;
current = current->next;
}
return count;
}
// Print all persons in the list
void LinkedList::print() const {
Node* current = head;
while (current != nullptr) {
current->person.print();
current = current->next;
}
}
// Recursive helper function to print the list in reverse order
void LinkedList::printReverseHelper(Node* node) const {
if (node == nullptr) {
return;
}
printReverseHelper(node->next);
node->person.print();
}
// Print all persons in the list in reverse order
void LinkedList::printReverse() const {
printReverseHelper(head);
}