Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Given the definitions of the classes Node and List below, define the member func

ID: 3842163 • Letter: G

Question

Given the definitions of the classes Node and List below, define the member function insert_after and the destructor.

The member function insert_after passes in the address to a Node (Node pointer) currently in the list and an integer value to be inserted into the list. This function should then create a new Node containing this integer value passed in and insert it into the list after the Node whose address is passed in. If the address passed in is 0, then insert the new Node at the front of the List.

The insert_after function is a private helper function that will be used within the insert_sorted public member function. You DO NOT need to define the insert_sorted function.

The destructor should ensure there are no memory leaks.

Notice there are no push_front, push_back or pop_front functions declared or defined for this List class. You may NOT define these or any other member functions, even as private helper functions.

struct Node {

};

class List {

public:
List() : head(0), tail(0) {}
~List(); //IMPLEMENT
void insert_sorted(int); //DON'T IMPLEMENT

private:

void insert_after(Node *, int); //IMPLEMENT

};

Explanation / Answer

void insert_after(Node* n,int t)
{
struct Node * newNode=(Node*)malloc(sizeof(struct Node));
newNode->data=t;
newNode->next=NULL;
if(n==0) //if address given is 0, so will insert at front
{
newNode->next=head;
head=newNode;
}
else //else insert after the given address of node
{
newNode->next=n->next;
n->next=newNode;
}
}

~List() //destructor
{
Node* tmp;
for(;head;head = tmp)
{
tmp = head->next;
delete head;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote