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

I need help creating a C program Function. The prototype is int add(struct node*

ID: 3881541 • Letter: I

Question

I need help creating a C program Function. The prototype is int add(struct node* list, int number)

This function should add a node to the list, to store the number in the list. The list should always be sorted, smallest to largest. The function returns 1 if successful, 0 if not successful (i.e. there is no memory left for creating a new node.)

This is how the struct node is set up:

struct node

{

int data;

struct node *next;

};  

Where data is the integer actually stored in the list and next is the momeory location of the next element, or NULL for the end of the list.

To add a number to the list, create a new node, search the list for the proper point to insert the new node, adjust the prior node's “next” field to point to the new node, and adjust the new node's “next” field accordingly.

Similar actions are taken for printing, searching and deleting.

You should use malloc(sizeof(struct node)) to get the address of a new node; and free(ptr) to release a node from memory (after deleting it, or at the end of the program).

Thanks in advanced! Please let me know if you need any additional information.

Explanation / Answer

#include<stdlib.h>
struct node
{
int data;
struct node *next;
};

int add(struct node* list, int number)
{
struct node *temp = (struct node*)malloc(sizeof(struct node));//creating node
  
   if(temp==NULL)//if node not created
   {
       return 0;   //not successfull
   }
   else
   {
       temp->data=number;//assigning number
       if(list==NULL)//if list is empty
       {
           list =temp;//  
       }
       while(list->next!=NULL)
       {
           if(list->data >= number)//finding position to place number
           {
               break;  
           }
           list=list->next;
      
       }
       int k;
       while(list->next!=NULL)//swapping upto last position
       {
          
               k= list->data;
               list->data=temp->data;
               temp->data = k;
              
               list=list->next;
       }
       //linking last node
      
       list->next = temp;
       temp->next=NULL;
       return 1;//sucessful
      
   }  
  
}

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