Insert New Node At the End of the Linked List

Insert New Node At the End of the Linked List

In this post, you will learn how to insert new node at the end of the Linked List, Code for the above task given below:

Insert New Node At the End of the Linked List


struct node
{   
    int data;
    struct node *next;
};

struct node *head = NULL;

void addLast(int val)
{
	struct node *New = malloc(sizeof(struct node));
	New->data = val;
	New->next = NULL;
	
	if(head==NULL){
	    head=New;
	}
	else{
	    struct node *Last = head;
	    while(Last->next!=NULL){
	        Last=Last->next;
	    }
	    Last->next = New;
	}
}

In this program, we are doing following things:

  1. Creating a structure for node, which contains a value and pointer. 
  2. After this we are creating a node head which is empty.
  3. Now allocating the memory in heap for the node New.
  4. Inserting the data in it and next part is the NULL.
  5. If head is empty then we are making the New node head.
  6. Else traverse from head and find the next NULL value so that we can change the NULL to the new node address and attach it to the new node which already contains NULL in its next part.

So this is how the function is working.


#include<stdio.h>
#include<stdlib.h>

struct node
{   
    int data;
    struct node *next;
};

struct node *head = NULL;

void insertAtEnd(int val)
{

	struct node *New = malloc(sizeof(struct node));
	New->data = val;
	New->next = NULL;
	
	if(head==NULL){
	    head=New;
	}
	else{
	    struct node *Last = head;
	    while(Last->next!=NULL){
	        Last=Last->next;
	    }
	    Last->next = New;
	}
}


void print()
{
    struct node *temp = head;

    while(temp != NULL)
    {
         printf("%d ", temp->data);
         temp = temp->next;
    }
}

int main()
{
     insertAtEnd(1);
     insertAtEnd(2);
     insertAtEnd(3);

     print();

     return 0;
}
Load comments