Implement the member function void insertAfterHead(int d) of the LinkedList clas
ID: 3800327 • Letter: I
Question
Implement the member function void insertAfterHead(int d) of the LinkedList class . The job of the function is to insert a new node with data d right after the head node. Your header will be
void LinkedList::insertAfterHead(int d)
The function does nothing if called on an empty list.
My incorrect code. I am having trouble with this last line.
void LinkedList::insertAfterHead(int d)
{
if(headPtr!= null)
{
head_>next = new Node
new Node->next =headPtr->next
}
Node * temp = headPtr;
Node * nodeToInsert = new Node() ;
nodeToInsert->data=d ;
nodeToInsert->next=temp ;
headPtr=nodeToInsert;
}
}
Explanation / Answer
Hi Friend please find my implementation
Please let me know in case of any issue.
void LinkedList::insertAfterHead(int d)
{
// Case 1: Header Node is null then add at front
if(headPtr == null)
{
headPtr = new Node(d);
}else{
Node *newNode = new Node(d); //creating new node
newNode->setNext(headPtr->getNext()); // pointing newNode's next to head's next
headPtr.setNext(newNode); // pointing head's next to newNode
}
}
}