Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

can somebody help me answer this question ? Write a function insertAtPositionN()

ID: 3784205 • Letter: C

Question

can somebody help me answer this question ?

Write a function insertAtPositionN() for a singly-linked list that has the following declaration and precondition: int insertAtPositionN (struct node **pHead, int n, int newData); Precondition: n > 0 and the list always has enough nodes to satisfy the position specified by n. The function should allocate memory for a new node, and initialize it with the newData value. It should then insert the node at the nth position in the list. The first node in the list starts at position 1. Note: you may NOT assume that a makeNode() function exists. The function should return 1 if a new node was created; 0 otherwise. Assume that struct node is defined as follows:

struct node

{

int data;

struct node *pNext;

};

Explanation / Answer

int insertAtPoitionN(struct node **pHead, int n, int newData)
{
node* previous = new node();
node* current = new node();
node* newNode = new node();
newNode->data = data;
int ctr = 0;
current = pHead;
if(pHead != NULL)
{
while(current->pNext != NULL && ctr != n)
{
previous = current;
current = current->pNext;
ctr++;
}
if(n==0)
return 1;
else if(current->pNext == NULL && n == ctr+1)
return 1;
else if(n >ctr+1)
return 0;
else
{
previous->pNext = newNode;
newNode->pNext = current;
return 1;
}
}
else
{
pHead = newNode;
newNode->pNext=NULL;
return 0;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote