Implement the insertFirst member function of the LinkedList class . Your header
ID: 3799453 • Letter: I
Question
Implement the insertFirst member function of the LinkedList class . Your header will be
void LinkedList::insertFirst(int d)
The job of insertFirst is to create a new Node with data equal to d and insert the Node at the front of the list. Don't forget to update headPtr and length. Also make sure you handle the case where the list is initially empty.
My incorrect attempt:
void LinkedList::insertFirst(int d){
int length;
Node * nodeToInsert = new Node(value, headPtr);
headPtr = nodeToInsert;
length++;
Explanation / Answer
Since nothing is given, I am assuming the node structure as:
struct Node{
int data;
Node *next;
}
void LinkedList::insertFirst(int d){
Node *nodeToInsert = (Node *)malloc(sizeof(Node *));
nodeToInsert->data = d;
nodeToInsert->next = NULL;
if(headPtr != NULL){
nodeToInsert->next = headPtr;
}
headPtr = nodeToInsert;
length++;
}