I'm a beginner and now I am trying to implement the class linked list which contains the function begin(). The function return well the first element in the list, but what i am trying to do is to return the iterator on the next position, for instance something like this:
List<int>::iterator iter2 = a.begin() + 2; // or iter2 = iter2 + 1;
cout <<iter2->data;
Where the output is garbage like 21213123..
So here I was thinking I should use an operator overloading+, here is my function:
template<class T>
Node<T>* operator+(const Node<T>& iter, const int& pos)
{
cout << "in"; for testing, but seems that doesnt even entry here
return NULL;
}
So can anyone help me? Thank you very much
P.S: Here is the class Node
template<class T>
class Node {
public:
T data;
Node* next;
Node() :data(0), next(NULL) {}
Node(T val, Node<T>* pointer = NULL) :data(val), next(pointer) {}
};
and list class
template<class T>
class List {
public:
typedef Node<T>* iterator;
typedef const Node<T>* const_iterator;
//constructors
List() { item = NULL; counter = 0; }
explicit List(int val) :counter(1) { item = new Node<T>(val); }
~List() { // to be made
}
//public functions
int size() { return counter; }
iterator begin() {
return item;
}
iterator end()
{
iterator last = item;
while (last->next != NULL)
{
last = last->next;
}
return last;
}
void push_front(const int& val) {
iterator newNode = new Node<T>(val, item);
item = newNode;
counter++;
}
void append(const int& val)
{
iterator newnode = new Node<T>(val);
newnode->next = NULL;
iterator last = item;
if (item == NULL)
{
item = newnode;
return;
}
while (last->next != NULL)
last = last->next;
last->next = newnode;
counter++;
}
int operator[](const int&);
private:
iterator item;
int counter;
};
coutis cached, try putting ` << endl` and see if you really dont get thereNodenot aniterator?iteratorshould not be a pointer type unless storage is continuous, like a vectorbeginfunction? That would be helpful in identifying what's going on.