Singly Linked List
Feb 16, 2012 at 7:22pm UTC
I am trying to make a singly linked list, but I am having problems. I cannot seem to be able to insert the first element after the head. I feel like my init() method is the problem. How can I insert the first element after the head node? Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
// Insert x before the iterator
iterator insert( iterator itr, const ObjectWithEquals & x )
{
cout << "Insert Called" << endl;
if (theSize == 0)
{
cout << "If called" << endl;
Node *p = itr.current;
theSize++;
cout << theSize << endl;
cout << itr.current << endl;
return iterator(head -> next = tail = new Node(x,p));
}
else
{
Node *n = itr.current;
currentItr = head -> next;
for (unsigned int i; i > theSize; i++)
{
cout << "for called" << endl;
currentItr++;
if (currentItr++ == itr.current)
{
cout << "if called" << endl;
currentNode = currentItr.current;
theSize++;
currentItr.current = NULL;
return iterator (currentNode -> next = new Node(x,n));
}
}
return NULL;
}
}
// Erase item at itr.
iterator erase( iterator itr )
{
Node *p = itr.current;
iterator retVal(p -> next);
for (unsigned int i; i > theSize; i++)
{
currentItr++;
if (currentItr++ == itr.current)
{
currentNode = currentItr.current;
theSize--;
currentNode -> next = p -> next;
delete p;
return retVal;
}
}
return NULL;
}
private :
unsigned int theSize;
Node *head;
Node *tail;
Node *currentNode;
iterator currentItr;
void init( )
{
theSize = 0;
head = new Node;
tail = new Node;
currentNode = new Node;
head -> next = NULL;
tail -> next = NULL;
currentNode -> next = NULL;
currentItr.current = NULL;
}
};
Feb 16, 2012 at 8:19pm UTC
These are all completely different memory addresses, you are correct, the problem begins here.
Head != Tail != Current right now.
1 2 3
head = new Node;
tail = new Node;
currentNode = new Node;
Topic archived. No new replies allowed.