I know there must be lots of these posted, but I search on google and on here, and I'm still having trouble.
We still haven't covered iterators fully and I'm having trouble with it. If anyone has a link to how iterators work (w/anything) that includes code, please let me know.
Anyway, I have a linked list class and an iterator class. I'll just try to post the relevant code.
One of the errors that I get is a warning that a reference to local variable 'it' is returned. I think I understand the error, but I'm not sure how to solve it. Any help is appreciated. Thanks.
**********LINKEDLIST CLASS AND MAIN***********
// LinkedList and main are together. they're not separate files.
Code:
#include <iostream>
#include <conio.h>
using namespace std;
template <class T>
class Node
{
public:
T data;
Node<T>* next;
Node<T>* prev;
Node(){ next = NULL; prev = NULL;}
};
#include "ListIterator.h"
template <class T>
class LL
{
public:
LL();
ListIterator<T> &begin();
ListIterator<T> &end();
private:
Node<T>* head;
friend class ListIterator<T>;
};
template <class T>
ListIterator<T>& LL<T>::begin()
{
ListIterator<T> it(head);
return it;
}
template <class T>
ListIterator<T>& LL<T>::end()
{
// This is wrong... I'm not sure how to do this...
ListIterator<T> it(head);
while(it.hasNext())
return it;
}
int main()
{
LL<int> obj;
obj.pushFront(3);
obj.pushFront(4);
//obj.printList(cout);
ListIterator<int> iter = obj.begin();
getch();
return 0;
}
*********LISTITERATOR CLASS*************
Code:
using namespace std;
template <class T>
class ListIterator
{
public:
Node<T> *current;
ListIterator() {}
ListIterator(Node<T>*);
bool hasNext();
bool hasPrevious();
T next();
T previous();
void insert(T val);
void remove();
};
//
template <class T>
ListIterator<T>::ListIterator(Node<T> *head)
{
current = head;
}
// Returns true if it has a next node
template <class T>
bool ListIterator<T>::hasNext()
{
return (current->next == NULL);
}
// Returns true if it has a previous node
template <class T>
bool ListIterator<T>::hasPrevious()
{
return (current->previous == NULL);
}
// Returns next node's data
template <class T>
T ListIterator<T>::next()
{
if(!this->hasNext())
return;
return (current->next->data);
}
// Returns previous node's data
template <class T>
T ListIterator<T>::previous()
{
if(!this->hasPrevious())
return;
return (current->prevous->data);
}
template <class T>
void ListIterator<T>::insert(T val)
{
Node<T> newNode = new Node<T>(val);
if(this->hasNext())
{
newNode->back = current;
newNode->next = current->next;
current->next->back = newNode;
current->next = newNode;
}
// Last one in list
else if(this->hasPrevious())
{
newNode->back = current;
current->next = newNode;
}
}
// Remove function
template <class T>
void ListIterator<T>::remove()
{
if(current == NULL)
return;
current->next->back = current->back;
current->back->next = current->next;
delete current;
}