1. Write a function deleteAtPositionN ) for a singly-linked list that has the fo
ID: 3878965 • Letter: 1
Question
1. Write a function deleteAtPositionN ) for a singly-linked list that has the following declaration and precondition: int deleteAtPositionN (struct node *pHead, int n, int *pData) Precondition: n>0 The function should find the node at position n, and delete it, using function free (). The data should be returned indirectly through pData, then the node must be released back to the heap. The first node in the list starts at position 1. The function should return 1 if a node was deleted; 0 otherwise. Assume that struct node is defined as follows: struct node int data; struct node *pNext; liExplanation / Answer
struct node {
int data;
struct node *pNext;
};
int deleteAtPositionN(struct node **pHead, int n, int *pData) {
struct node *temp = *pHead;
struct node *nextPtr;
int index = 2;
if(n == 1) {
if(temp == NULL) {
return 0;
}
*pData = temp->data;
*pHead = temp->pNext;
free(temp);
return 1;
}
while(temp->pNext != NULL) {
if(n == index) {
*pData = temp->pNext->data;
nextPtr = temp->pNext->pNext;
free(temp->pNext);
temp->pNext = nextPtr;
return 1;
}
temp = temp->pNext;
index++;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.