Thread: How to Inserting a new node in a linked list

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

    How to Inserting a new node in a linked list

    How to Inserting a many nodes in a linked list

    Here is my code.


    Code:
    #include <stdio.h>#include <stdlib.h>
    
    
    struct node
    {
        int data;
        struct node *next;
    };
    
    
    struct node* front(struct node *head, int value)
    {
    	struct node *p;
    	p=malloc(sizeof(struct node));
    	p->data=value;
    	p->next=head;
    	return (p);
    }
    
    
    int main(void)
    {
    	struct node *head = NULL;
        head=front(head,10);
    
    
    	if(head == NULL)
        {
            printf("NULL\n");
        }
        else
        {
            printf("%d\n", head -> data);
        }
    	
    	return 0;  
    }
    20
    Could anyone help me with this.



  2. #2
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    945
    What is your question? What do you need help with?

    By the way, when I run your code it prints "10", as I would expect.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You mean like
    Code:
    for ( int i = 0 ; i < 10 ; i++ ) {
        head=front(head,i);
    }
    Work on a function to print your list.
    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.

  4. #4
    Registered User
    Join Date
    May 2017
    Posts
    129
    Quote Originally Posted by Salem View Post
    You mean like
    Work on a function to print your list.
    I want to add and print N nodes

    Code:
     void show(struct node *head){     
         struct node *q;
         q = head;
         while (q!=NULL){
               printf("%d\n",q->data);
               q = q->next;
               }
     
         }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem in output of code(Inserting node in linked list)
    By Kunal1997 in forum C Programming
    Replies: 3
    Last Post: 09-03-2016, 01:37 AM
  2. Two Question About Inserting Node In the Linked List
    By hefese in forum C Programming
    Replies: 10
    Last Post: 08-07-2012, 12:24 PM
  3. problem inserting node in middle of list
    By c_weed in forum C++ Programming
    Replies: 3
    Last Post: 12-22-2010, 09:14 PM
  4. Replies: 7
    Last Post: 11-04-2010, 01:18 PM
  5. Replies: 3
    Last Post: 12-06-2008, 07:54 PM

Tags for this Thread