Linked List in C- Insert Node at End of Linked List

Linked List in C- Insert Node at End of Linked List

Linked List in C- Insert Node at End of Linked List

DATA STRUCTURES IN C – LINKED LIST (20 PROGRAMS)

Linked List in C- Insert Node at End of Linked List :

Source Code :

#include<stdio.h>
struct node *head=NULL;
//Pointer to store the staring node of the linked list
//Always stores the address location of first node

struct node *end=NULL;
//Pointer to store the last node of the linked list
//Declared as global variable since it is accessed by multiple functions

struct node
{
	    //Structure named node to store integer in variable data and a pointer variable which can store address location of next node
    	int data;
    	struct node *next;
};

void insertatend(int data)
{
    	//Function to insert new node at the end of linked list
    	struct node *temp = (struct node*)malloc(sizeof(struct node));
    	//Creating new node in heap
    	//Dynamic memory allocation

    	temp->data=data;
    	temp->next=NULL;
    //Assigning the data obtained and making the next pointer of temp node point to NULL

    	if(head==NULL)
    	{
        		//Executed only if head is NULL
        		//Executed only once i.e. when inserting first node
        		head=temp;
        		end=temp;
        		return;
    	}
    	end->next=temp;
    	//Making last node point to newly created temp node

    	end=temp;	
    	//Making newly created temp node as end node
}

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

int main()
{

    	insertatend(1);
    	print();
    	//Inserting node at end of linked list

    	insertatend(2);
    	print();
    	//Inserting node at end of linked list

    	insertatend(3);
    	print();
    	//Inserting node at end of linked list

    	return 0;
}

Output :

List:
1

List:
1
2

List:
1
2
3

[ YOU MAY ALSO LIKE ]

Leave a Reply