I tried to implement a singly linked list myself, sorry it is not commented but I think it should be pretty self-explanatory, if not feel free to comment. I know that using namespace std; is not optimal, but I figured it would be okay for this little example. Same goes for defining the class right in the main.cpp file (and in the declaration). I have two questions:
- Is this even a correct implementation or did I miss something important? The methods worked as expected for me.
- Would it make any sense to use smart pointers here? If yes, why? And what would I have to change for it to work?
Thank you for your time, I would appreciate any answers! :)
#include <iostream>
using namespace std;
struct Node
{
int32_t data;
Node* next;
};
class linked_list
{
public:
linked_list() : last{ NULL }, tmp{ NULL }, begin{ NULL } {};
~linked_list()
{
clear();
}
void push_back(int32_t data)
{
if (begin)
{
tmp = new Node;
tmp->data = data;
tmp->next = NULL;
last->next = tmp;
last = tmp;
tmp = NULL;
}
else
{
begin = new Node;
begin->data = data;
begin->next = NULL;
last = begin;
}
}
void display_all()
{
if (begin)
{
tmp = begin;
while (tmp)
{
cout << tmp->data << endl;
tmp = tmp->next;
}
tmp = NULL;
}
else
{
cout << "List is empty." << endl;
}
}
void clear()
{
while (tmp != last)
{
tmp = begin->next;
delete begin;
begin = tmp;
}
delete last;
begin = NULL;
tmp = NULL;
last = NULL;
}
private:
Node* last;
Node* begin;
Node* tmp;
};
PS:
(Someone told me this would fit better on this site than on Stack Overflow so I am reposting.)
display_all
: Instead of hard-coding it as output tocout
, allow output to an arbitrary ostream. Better yet, rewrite this to overrideoperator <<
\$\endgroup\$