Skip to content

Instantly share code, notes, and snippets.

View BogdanAriton's full-sized avatar
🏠
Working from home

Bogdan Ariton BogdanAriton

🏠
Working from home
View GitHub Profile
// what this does is just simply return a pointer to the first element in the vector
std::vector<type>::iterator myItr = myVector.begin();
// we can simply for loop over the items using the iterator
for (; myItr != myVector.end(); ++myItr)
{
// print them out
}
// You could simply use a for each loop to get the items directly
for (auto &item : myVector)
struct Node
{
using node_ptr = std::unique_ptr<Node>;
Data data{}; // what we store
node_ptr next = nullptr; // link to the next element
};
template <typename Data>
class LinkedList
{
private:
// the node holds only the data we want to store
// and the link to the next node in the list
struct Node
{
using node_ptr = std::unique_ptr<Node>;
Data data{};
std::size_t l_size() const noexcept { return size; }; // gets back the size of the list (hence the l_ in the name)
bool isEmpty() const { return l_size() == 0; }; // checks if the size is zero which indicates that the list is empty
void push_front(const Data &data)
{
// if the list is empty we're going to add head
if (isEmpty())
{
head = std::make_unique<Node>(data, nullptr);
}
else
{
node_ptr newNode = std::make_unique<Node>(data, nullptr);
void push_back(const Data &data) noexcept
{
// if the list is empty we're going to add head
if (isEmpty())
{
head = std::make_unique<Node>(data, nullptr);
}
else
{
Node *current = head.get();
void clear() noexcept
{
if (!isEmpty())
{
Node *current = head.get();
while (current != nullptr)
{
Node *temp = current;
temp = nullptr;
current = current->next.get();
void reverse() noexcept
{
// to reverse the list we simply have to switch the nodes until the head becomes the tail
node_ptr current;
current = std::move(head);
node_ptr next = nullptr;
node_ptr temp = nullptr;
while (current != nullptr)
{
// copy constructor
LinkedList(const LinkedList &other) noexcept
{
// the copy constructor will have to go through all the nodes in other and make a copy of them into our list
// for that we need to be able to add the new nodes to this list, basically we need to copy the data and recreate the links
std::cout << "*** Copy constructor ***" << '\n';
if (other.head == nullptr)
return;
head = std::make_unique<Node>(other.head->data); // we need to know who head is - thus it needs to be initialized separately
LinkedList(std::initializer_list<Data> listOfItems) noexcept
{
if (listOfItems.size() != 0)
{
auto it = listOfItems.begin(); // will use the iterator for the list to get the first element
head = std::make_unique<Node>(*it); // The head is our first element
size++; // added first item
Node *current = head.get();
++it;
for (; it != listOfItems.end(); ++it) // we traverse the list using the defined iterator