This is homework
I'm working on implementing a linked list class for my C++ class, and the copy constructor has be very confusing for me.
The linked list is comprised of structs called Elems:
struct Elem
{
int pri;
data info;
Elem * next;
};
Elem * head;
info is a separate, custom class that is stored in the Elem.
the signature for the copy constructor is:
linkedList::linkedList( const linkedList &v )
The issue I am having is mostly taking my logic and actually writing it as code.
My general idea is to:
- Set head to v.head (head = v.head)
- Set the Elem's values to v's (pri = v.pri , info = v.info , next = v.next)
- Iterate through, repeating step 2.
Is this the general idea?
Any help would be great. Remember, this is homework, so no direct answers please!
Thank you for your time
====================================================================================================================================================================
Thanks for your time everybody!
I think I have it figured out:
//Copy Constructor
LinkedList::LinkedList( const LinkedList &v )
{
Elem * p1 = 0;//current
Elem * p2 = 0;//next
if( v.head == 0 )
head = 0;
else
{
head = new Elem;
head -> pri = v.head -> pri;
head -> info = v.head -> info;
p1 = head;
p2 = v.head -> next;
}
while( p2 )
{
p1 -> next = new Elem;
p1 = p1 -> next;
p1 -> pri = p2 -> pri;
p1 -> info = p2 -> info;
p2 = p2 -> next;
}
p1 -> next = 0;
}
I'm pretty sure that works. I drew some logical pictures to help, and I didn't run into any issues.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…