Implement the array constructor of the LinkedList class . Your header will be Li
ID: 3800318 • Letter: I
Question
Implement the array constructor of the LinkedList class . Your header will be
LinkedList::LinkedList(int myArray[], int size)
The function will insert the values from myArray into the list so that the values end up in the same order as they were in the array . (Hint: loop through the array from right to left and call insertFirst.)
This was my incorrect attempt
LinkedList::LinkedList(int myArray[], int size)
{
headPtr->value=(array[0]);
Node *currentPtr = headPtr;
for (int i = 0; i < size; ++i)
{
currentPtr->setNext(new Node(array[i]));
}
}
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
LinkedList::LinkedList(int myArray[], int size)
{
// creating header node with first element of array
headPtr = new Node(myArray[0]);
Node *currentPtr = headPtr;
// iterating from 1 to size-1
for (int i = 1; i < size; ++i)
{
currentPtr->setNext(new Node(myArray[i]));
currentPtr = currentPtr->getNext();
}
}