How is this designed so far?
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <memory>
#include <iostream>
template <typename T> using ptr = std::shared_ptr<T>;
template <typename V>
class LinkedList
{
private:
class Node
{
private:
V data;
ptr<Node> next;
public:
Node() : next{} {}
Node(V _data) : next{}, data{_data} {}
ptr<Node>& getNext(){
return this->next;
}
V getData(){
return this->data;
}
};
ptr<Node> head;
ptr<Node> tail;
size_t _size;
public:
LinkedList() : head{}, tail {}, _size{} {}
void add(V _data){
auto _tmp = std::make_shared<Node>(_data);
if(isEmpty()){
head = _tmp;
tail = _tmp;
} else {
tail->getNext() = _tmp;
tail = _tmp;
}
_size++;
}
bool isEmpty(){
if(head == nullptr) return true;
else return false;
}
V operator[](int index){
int _c {};
ptr<Node> tmp = head;
while(tmp!=nullptr){
if(_c == index){
break;
}
tmp = tmp->getNext();
_c++;
}
return tmp->getData();
}
void addFirst(V _data){
auto _tmp = std::make_shared<Node>(_data);
if(isEmpty()){
_tmp->getNext() = head;
head = _tmp;
tail = _tmp;
} else {
_tmp->getNext() = head;
head = _tmp;
}
_size++;
}
template <typename V>
void insertAfter(int index, V _data){
auto _tmp = std::make_shared<Node>(_data);
std::shared_ptr<Node> _curr;
std::shared_ptr<Node> _afterIndex;
if(index<0 || index > size()-1){std::cerr << "__INDEX_OUT_OF_RANGE__" << std::endl;}
else {
int _c {};
ptr<Node> tmp = head;
while(tmp!=nullptr){
if(_c == index){
_curr = tmp;
_afterIndex = _curr->getNext();
break;
}
tmp = tmp->getNext();
_c++;
}
_curr->getNext() = _tmp;
_tmp->getNext() = _afterIndex;
_size++;
}
}
void traverseList(){
{
ptr<Node> tmp = head;
while(tmp!=nullptr){
std::cout << tmp->getData() << std::endl;
tmp = tmp->getNext();
}
}
}
size_t size(){ return _size; }
};
#endif // LINKEDLIST_H
#include "linkedlist.h"
#include <string>
int main(){
auto list = std::make_shared<LinkedList<std::string>>();
list->addFirst("Bob");
list->add("Carl");
list->add("Mario");
list->add("Elliot");
list->addFirst("Neo");
list->insertAfter(0,"I'm inserted after " + (*list)[0]);
for (int i {} ; i < list->size(); ++i) {
std::cout << (*list)[i] << std::endl;
}
return 0;
}