Thread: create new node and return the reference in function

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    110

    create new node and return the reference in function

    I am creating three nodes in linked list

    Code:
    #include<stdio.h>#include<stdlib.h>
    
    struct Node
    {
      int data;
      struct Node *next;
    };
      int main()
    {
      struct Node* head = NULL;
      struct Node* second = NULL;
      struct Node* third = NULL;
      struct Node *temp = NULL;
    
    
    
    
      head  = (struct Node*)malloc(sizeof(struct Node));
      second = (struct Node*)malloc(sizeof(struct Node));
      third  = (struct Node*)malloc(sizeof(struct Node));
    
      head->data = 1;       //assign data in first node
      head->next = second;  // Link first node with second
    
      second->data = 2;     //assign data to second node
      second->next = third;
    
      third->data = 3;     //assign data to third node
      third->next = NULL;
    
    
       temp = head;
      while (temp != NULL)
      {
         printf(" %d ", temp->data);
         temp = temp->next;
      }
    
      return 0;
    }
    I want to create function that would add new node and return the reference

    Code:
    int New_Node( int data){
      // make a new node and return the reference 
    }
    How to create new node and return the reference in function ?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,662
    OK, so make it return it then
    Code:
    struct Node * New_Node( int data){
      // make a new node and return the reference 
      struct Node *p = malloc(sizeof(*p));
      p->data = data;
      p->next = NULL;
      return p;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-20-2018, 11:48 AM
  2. how to create a function return with char* array
    By tester1234 in forum C Programming
    Replies: 7
    Last Post: 12-09-2015, 11:25 AM
  3. Replies: 4
    Last Post: 01-23-2008, 06:21 AM
  4. Replies: 6
    Last Post: 04-09-2006, 04:32 PM

Tags for this Thread