Decided to write something simple and came up with idea to write simple single linked list in C++ to improve my knowledge about pointers and memory management in C++, and wrote this:
#include <iostream>
void pause() {
std::cout << '\n' << "Press <Enter> to continue...";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
//std::cin.get(); // Use when not debug
} // PAUSE
namespace LinkedList {
class LinkedList {
private:
int m_value{};
LinkedList* m_next{ nullptr };
public:
LinkedList(int value = 0) : m_value{ value } {}
void Add(int value) {
if (!m_next) { m_next = new LinkedList{ value }; } // If it's the last element then add
else { m_next->Add(value); } // And if not go up in linked list
}
void Delete(int value) {
if (m_next->m_value == value) {
LinkedList* tmp_ptr{ m_next->m_next };
delete m_next; m_next = tmp_ptr; return;
} // If next value equals the value to delete then redirect the current element to element, after that, we search for
if (!m_next) { return; } // If no element after, return
else { m_next->Delete(value); } // If we can go upper, go
}
LinkedList* Find(int value) {
if (m_value == value) { return this; } // If found return pointer to it
else if (m_next) { m_next->Find(value); } // If still can go up, go
else { return nullptr; } // If not found and nowhere to go up return nullptr
} // Return a pointer to element which contains certain number
friend std::ostream& operator<<(std::ostream& os, LinkedList list);
};
std::ostream& operator<<(std::ostream& os, LinkedList element) {
while (true) {
os << element.m_value << " ";
if (!element.m_next) { return os; } // If it's a last element then return
else { element = *element.m_next; } // If not go up
}
}
}
int main() {
LinkedList::LinkedList test{ };
int input{};
while (std::cin >> input) { test.Add(input); } // Ask for input until cin fails
std::cout << test;
pause();
return 0;
}
Is this any good or it could have been written better?
Delete
also contains theFind
logic. You should make that common code. \$\endgroup\$