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

Write a function insertAtPositionN () for a doubly-linked list that has the foll

ID: 3596666 • Letter: W

Question

Write a function insertAtPositionN () for a doubly-linked list that has the following declaration and precondition:

int insertAtPositionN (struct node **pHead, int n, int newData);

Precondition: n > 0.

The function should navigate to position n in the list. If position n exists, then the function should allocate memory for a new node, and initialize it with the newData value. It should then insert it into the nth position. The first node in the list starts at position 1. Note: you may NOT assume that a makeNode( ) function exists. Also, the list may be empty or not contain n nodes. If position n does not exist, then the function should return 0; otherwise 1 is returned. Assume that struct node is defined as follows:

struct node
{
int data;
struct node *pNext;
struct node *pPrev;
} Node;

Explanation / Answer

int insertAtPositionN (struct node **pHead, int n, int newData);

{

int i;

struct node* temp=(struct node*) malloc(sizeof(node)),*temp1,*temp2;

temp->data=newData;

if(get==1 || head==NULL)

{

if(pHead==NULL && n==1) //for insertion at beginning

{

temp->pPrev=temp->pNext=NULL;

pHead=temp;

return;

}

pHead->pPrev=temp;

temp->pPrev=NULL;

temp->pNext=pHead;

pHead=temp;

return 1;

}

temp1=pHead;

for(i=0;i<n-2;i++) //for insertion at any other position .

{

temp1=temp1->pNext;

if(temp1==null)

return 0;

}

temp->pNext=temp1->pNext;

temp->pPrev=temp1;

temp1->pNext=temp;

temp2=temp->pNext;

if(temp2)

temp2->pPrev=temp;

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