C++ Programming Exercise: A NumList class is implemented using a singly linked l
ID: 640844 • Letter: C
Question
C++ Programming Exercise:
A NumList class is implemented using a singly linked list. The member variables are int length and Node* headPtr. Node is a struct with members int value and Node* next. In each part below implement the class member as if defined outside the class declaration.
a. Define the default constructor that sets headPtr to NULL and length to 0.
b. Define the copy constructor.
c. Define the destructor.
Can someone give me the code only for the default constructor, copy constructor, and destructor?
Explanation / Answer
// default constructor
NumList::NumList(){
length = 0;
headPtr = NULL;
}
// copy constructor
NumList::NumList(NumList &l){
length = l.length;
Node *temp = l.headPtr;
Node *temp2 = NULL;
while(temp != NULL){
Node *newone = new Node;
newone->value = temp->value;
newone->next = temp->next;
if(headPtr == NULL){
headPtr = newone;
temp2 = headPtr;
}
else{
temp2->next = newone;
temp2 = temp2->next;
}
temp = temp->next;
}
}
// destructor
NumList::~NumList(){
Node *temp1 = headPtr, temp2;
while(temp1 != NULL){
temp2 = temp1->next;
delete temp1;
temp1 = temp2;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.