all.
I'm currently working on my singly linked list and hit a road block with my iterator class. This is so far what I have and I'll start with the node, then the singly linked list, then the iterator it self.
My nodes look like this currently. I apologize in advance for "syntax errors" shown in my code below. I can't properly indent with out compromising the code text in this website. I'm still getting use to how stackoverflow works.
#include <iostream>
#include <cstddef>
class SingleNode
{
private:
int key_;
SingleNode * next_;
public:
SingleNode(int key, SingleNode * next = NULL)
: key_(key), next_(next)
{
}
void set_key(int key)
{
key_ = key;
}
int get_key() const
{
return key_;
}
int & get_key()
{
return key_;
}
SingleNode * get_next() const
{
return next_;
}
SingleNode * set_next(SingleNode * next)
{
next_ = next;
}
};
std::ostream & operator<<(std::ostream & cout, const SingleNode & node)
{
cout << "< " << ' ' << &node << ' '
<< "key: " << node.get_key() << ' '
<< "next: " << node.get_next() << '>';
return cout;
}
Now for my SinglyLinked list
#include <iostream>
#include <cstddef>
#include "SingleNode.h"
class SingleNode;
class SingleLinked
{
private:
SingleNode * phead_;
public:
SingleLinked()
: phead_(NULL)
{
}
class iterator
{
friend class SingleLinked;
private:
SingleNode * p;
iterator(SingleNode * phead)
: p(phead)
{
}
public:
iterator()
: p(NULL)
{
}
int & operator*()
{
return p->get_key();
}
int & operator++()
{
p = p->get_next();
}
};
iterator begin() const
{
return iterator(phead_);
}
SingleNode * get_phead() const
{
return phead_;
}
SingleNode * insert_head(int key)
{
phead_ = new SingleNode(key, phead_);
}
SingleNode * insert_tail(int key)
{
SingleNode * p = new SingleNode(key, NULL);
SingleNode * r = p;
SingleNode * q = phead_;
while (q->get_next() != NULL)
{
q = q->get_next();
}
q->set_next(r);
}
void delete_head()
{
SingleNode * p = phead_;
phead_ = p->get_next();
}
void delete_tail()
{
SingleNode * p = phead_;
while (p->get_next() != NULL)
{
p = p->get_next();
}
SingleNode * r = phead_;
while (r->get_next() != p)
{
r = r->get_next();
}
r->set_next(NULL);
}
void print()
{
while (phead_ != NULL)
{
std::cout << *phead_ << std::endl;
phead_ = phead_->get_next();
}
}
};
The idea is this, I want to use the SingleLinked class as a friend class to the iterator. That way, once the SingleLinked class is initialized in the main, it automatically constructs the iterator inside of it. This runs into some problems as soon as I start using the begins method.
This is the main so far.
#include <iostream>
#include "SingleLinked.h"
int main()
{
SingleLinked list;
list.insert_head(1);
list.insert_tail(2);
typename SingleLinked::iterator p = list.begin();
std::cout << *p << std::endl;
return 0;
}
Once I try to cout that iterator p, it shows a segmentation fault in the console. What is going inside my SingleLinked class itself that is causing this?