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

Write a function deleteAtPositionN () for a singly-linked list that has the foll

ID: 3886135 • Letter: W

Question

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. 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: };

Explanation / Answer

int deleteAtPositionN(struct Node **pHead, int n, int *pData)

{

    // Store head node

    struct Node* temp = * pHead , *prev;

    // If head node itself holds the key to be deleted

    if (temp != NULL && n==1)

    {

      *pData= temp->data;

        * pHead = temp->pNext;   // Changed head

        free(temp);               // free old head

        return 1;

    }

    // move n levels and keep track of the

    // previous node

   for(int i=1;i<n;i++)

   {
     

      prev = temp;

      temp = temp-> pNext;

    

   }

    // If nth item was not present in linked list

    if (temp == NULL) return 0;

    // Unlink the node from linked list

    *pData= temp->data;

    prev-> pNext = temp-> pNext;

    free(temp); // Free memory
    return 1;

}

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