Insert Node at the end of linked list

C Program to insert node at the end of linked. Program to add node at the end of linked list.


C Program:

#include<stdio.h>
#include<stdlib.h>
 
struct Node
{
    int data;
	struct Node *next;
};
 
/* Function to create new node to insert in linked list 
that take an interger as arguement and return the
 address of node */
struct Node *CreateNode(int n)
{
	/* Function to create new Node to insert node in
	 linked list */
 struct Node *newNode=(struct Node*)malloc(sizeof(struct Node));
	newNode->data = n;
	newNode->next = NULL;
	return newNode;
}
 
struct Node *InsertAtEnd(struct Node *head,int n)
{
	struct Node *newNode = CreateNode(n);
	struct Node *temp = head;
 
	/* If head is pointing to NULL then at node at 
	first position */
	if(head==NULL)
	{
		head = newNode;
	}
	else
	{
	/* If there is node/nodes in linked list then reach 
	at the end node of linked list and then point end 
	node to new node */
 
		while(temp->next!=NULL)
	{
		temp = temp->next;
	}
	/* Connect new node to linked list */
	    temp->next = newNode;
	}
 
	return head;
 
}
 
void PrintList(struct Node *head)
{
	struct Node *curr = head;
 
	/* If head is pointing to NULl it means list is 
	empty */
	if(curr==NULL)
	{
		printf("List is empty\n");
	}
	else
	{
		while(curr!=NULL)
	{
		printf("%d ",curr->data);
		curr = curr->next;
	}
	}
	printf("\n");
}
int main()
{
	struct Node *head=NULL;
 
	/*Print list when there is not any node in list
	or list is empty */
	PrintList(head);
 
	head = InsertAtEnd(head,54);
	head = InsertAtEnd(head,65);
	head = InsertAtEnd(head,49);
	head = InsertAtEnd(head,98);
	PrintList(head);
 
	return 0;
}




Popular posts from this blog