#include <iostream>
using std::cout;
using std::endl;
class LinkedList
{
struct Node
{
int x;
Node *next;
};
Node *head;
// get a pointer to the last node in the list.
// returns: head if the list is empty.
Node* last_node()
{
Node* cur = head;
while (cur->next)
cur = cur->next;
return cur;
}
public:
LinkedList()
: head(new Node { -1, nullptr })
{
}
// If you absolutely have to have a constructor that adds a node:
LinkedList(int adds) : LinkedList()
{
add(adds);
}
~LinkedList() // destructor
{
// Free all of the nodes we created
Node *next;
for (Node* cur = head; cur != nullptr; cur = next) {
next = cur->next;
delete cur;
}
}
void add(int adds)
{
Node* tail = last_node();
tail->next = new Node { adds, nullptr };
cout << "added: " << tail->next->x << endl;
}
bool empty() const
{
return (head->next == nullptr);
}
// returns: value of the last node (-1 if list is empty)
int back()
{
return last_node()->x;
}
// Normal implementation requires caller to check !empty() first:
// returns: value of the first non-head node
// if the list is empty, undefined behavior.
int front()
{
return head->next->x;
}
// alternatively:
// returns: value of the first non-head node or -1 if the list is empty.
int front_safe()
{
return (head->next) ? head->next->x : head->x;
}
};
int main()
{
LinkedList lt;
lt.add(1);
lt.add(2);
lt.add(3);
lt.add(4);
cout << lt.front() << endl;
cout << lt.back() << endl;
}