Implement the findPre function of the LinkedList class . Node * LinkedList::find
ID: 3799636 • Letter: I
Question
Implement the findPre function of the LinkedList class .
Node * LinkedList::findPre(int d)
The job of this function is to return a pointer to the node the precedes a node with data equal to d. If d only occurs in the head node or d doesn't occur in any node, then the function should return a pointer to the last node in the list. If the list is empty then the function should return the null pointer.
This is my current attemp, it is incorrect
Node * LinkedList::findPre(int d){
Node * pre = headPtr;
for (int i = 1; i < position-1; i++)
pre = pre->next;
// how pre points to the node right before the one we want to remove.
Node *temp = pre->next;
pre->next = temp->next;
}
Explanation / Answer
HI, Please find my implementation.
Please let me know in case of any issue.
Node * LinkedList::findPre(int d){
if(headPtr == NULL)
return NULL;
// if there is only one node(the first and last node is same), then return headPtr (last node)
if(headPtr->next == NULL)
return headPtr;
Node *pre = headPtr;
Node *current = headPtr->next;
while(current != NULL){
if(current->data == d)
return pre;
pre = current;
current = current->next;
}
return pre; // returning last node
}