can somebody help me answer this question Write a function
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;
};
Solution
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;
}
}
