C++ I have a small question in this piece of code. I wanna add that if a positio
ID: 3866341 • Letter: C
Question
C++ I have a small question in this piece of code. I wanna add that if a position is not found return -1; Please if you do not know don't answer it. and no it is not as simple as:
if (head == NULL)
{
return -1;
} //This would be wrong and totally wrong so please chegg answerers don't answer if you do not know
int NumberList::insertByPosition(int value, int position)
{
ListNode *newNode = new ListNode;
newNode->value = value;
newNode->next = NULL;
if (head == NULL)
{
head = newNode;
return;
}
if (position == 0)
{
newNode->next = head;
head = newNode;
return;
}
ListNode *n = head;
int nodesToPass = 1;
while (nodesToPass <= position)
{
if (n->next == NULL || nodesToPass == position)
{
ListNode *tempPtr = n->next;
n->next = newNode;
newNode->next = tempPtr;
return;
}
n = n->next;
nodesToPass++;
}
Explanation / Answer
Your current implementation is not returning anything. You just included return statements (return;), but you are not actually returning anything, like return 1; So, Let us assure that the expected return value is +1, if position is found the node is successfully inserted. -1, if the position is not found.
Because of unavailability of the ListNode and Numberlist class, I couldn't test it and paste the output
C++ function :
int NumberList::insertByPosition(int value, int position)
{
ListNode *newNode = new ListNode;
newNode->value = value;
newNode->next = NULL;
//If the head node is null, our new node will be the head
if (head == NULL)
{
head = newNode;
//you must return +1, instead of just writing return
return 1;
}
//If we have to insert at position 0, this will be our new head.
if (position == 0)
{
newNode->next = head;
head = newNode;
return 1;
}
ListNode *n = head;
int nodesToPass = 1;
while (nodesToPass <= position)
{
//Your logic is that , If we reach the end of the list or this is our current position, insert the node at this position
//Since you want to return -1, if the position is not found, i.e end of the list is reached. you must remove the condition n->next = null ,
//and seperate the condition. Because of this condition the node is inserted at the end if end of the list is reached.
if(n->next==NULL){
//This means end of the list is reached and position is not found.
return -1;
}
if (/*n->next == NULL || */nodesToPass == position)
{
ListNode *tempPtr = n->next;
n->next = newNode;
newNode->next = tempPtr;
//If the node is successfully inserted, +1 is returned.
return 1;
}
n = n->next;
nodesToPass++;
}
return -1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.