How do I write a function to insert a node in C? The directions for this functio
ID: 3569401 • Letter: H
Question
How do I write a function to insert a node in C? The directions for this function are:
Here is a step by step description of what you should do to insert an integer newval into an ordered linked list with first node pointer p:
1. Declare a Node pointer variable q, dynamically allocate a Node as the target of q and set the data value of the new node to newval.
2. If the list is empty or newval is less than or equal to the data value in the first node of the list, set the next pointer of q to the first node pointer (p) and return q.
3. Use a Node pointer tmp to traverse the list until it either reaches the last node or reaches a Node whose following node has data value greater than or equal to newval.
4. Insert the target of q after the target of tmp and return p (the original first node pointer).
I'm really lost on how to follow these direction.
Explanation / Answer
Struct ListNode{
int data;
Struct ListNode * next;
}
void InsertInLinkList(struct ListNode **head,int data,int position){
int k=1;
Struct ListNode *p,*q,*newnode;/*p meant to point to current,q meant to point to previous one of current,see below to understand better */
newNode=(ListNode*)malloc(sizeof(Struct ListNode));
if(!newnode){
printf("Memory Error");return;
}
newNode->data=data;
*p=*head;
//insert at beginning
if(position==1){
newNode->next=p;
*head=newNode;
}
else{
//Traverse until position where u want to insert
while((p!=NULL) &&k<position){
k++;
q=p;
p=p->next;
}
q->next=newNode;
newNode->next=p;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.