I am trying to implement a LinkedList which can be iterated through in c++.
I have therefore made an Iterator class, such that dereferencing an Iterator would return the first element. However, this has not been working. When I then instantiate a new int LinkedList and attempt to access the first element by dereferencing the result of begin(), I do not retrieve the first element of the list, but a 10 digit number such as '1453755360'
My node class is just composed of two right/left node pointers and a data variable
linkedlist class
template <typename T>
class LinkedList{
public:
LinkedList(){
count =(0);
head =(nullptr);
tail =(nullptr);
}
void push_head(T input){
Node<T> newNode = Node<T>(input);
newNode.left = nullptr;
newNode.right = head;
head = &newNode;
count++;
}
T front(){
T& data = (head->data);
return data;
}
void push_tail(T input){
Node<T> newNode = Node<T>(input);
newNode.right = tail;
newNode.left = nullptr;
tail = &newNode;
count++;
}
T back(){
T& data = (tail->data);
return data;
}
Iterator<T> begin(){
Iterator<T> test = Iterator<T>(head);
return test;
}
private:
int count;
Node<T> *head;
Node<T> *tail;
};
Here is where I am testing the code
LinkedList<int> ll;
ll.push_tail(7);
ll.push_tail(9);
if (*(ll.begin()) == 9) {
cout << "pass" << endl;
} else {
cout << "returned : " << *(ll.begin()) << endl;
}
Node<T> newNode = Node<T>(input);will be destroyed when the scope ends.