I am really confused here as to why this copy constructor is not working! I am creating an iter
pointer that points to the same ListNode as head
, but when I copy stuff from s
to it
, head
and iter
are not connected!
In other words when printing head, only the first character is in there, but if I were to iterate through iter
, the rest of the list is in there. Why isn't iter
and head
pointing to the same objects?!
NOTE: This is a linked list being used to implement a class called MyString.
struct ListNode {
char info;
ListNode *next;
ListNode () : info('0'), next(0) {}
ListNode (char c) : info (c), next(0) {}
};
class MyString {
private:
ListNode *head;
MyString::MyString(const MyString & s) {
if (s.head == 0)
head = 0;
else {
head = new ListNode (s.head -> info);
++NumAllocations;
ListNode *iter = head;
for (ListNode *ptr = s.head -> next; ptr != 0; ptr = ptr ->next) {
iter = iter -> next;
iter = new ListNode (ptr -> info);
++NumAllocations;
}
}
}
}
You don't appear to be attaching the list to the head anywhere.
Try this.
MyString::MyString( const MyString & s ) {
if ( s.head == 0)
head = 0;
else {
head = new ListNode (s.head -> info);
++ NumAllocations;
ListNode *iter = head;
for (ListNode *ptr = s.head -> next; ptr != 0; ptr = ptr ->next) {
iter -> next = new ListNode (ptr -> info);
iter = iter -> next;
++ NumAllocations;
}
printList(head);
}
}
Notice the attachment of iter->next. You were just creating a new node and doing nothing with it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments