Insertion at the End In Single Linked List Using C

Description

This program is used to insert elements at the End of a list in single linked list data structure.


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

struct node
{
 int data;
 struct node* next;
};
struct node *head=NULL;

void insend();
void print();

void main()
{
  int choice;
  do
  {
   printf("\n__MENU__\n1.Insert at the End\n2...EXIT...\n");
   printf("\nENTER your choice\n");
   scanf("%d",&choice);
   switch(choice)
   {
    case 1 :insend();break;
    case 2:printf("~~~~~~~THANK YOU~~~~~~~\n");break;
   default:printf("INVALID input !!!");break;   
  }
  }while(choice!=2);
}

void insend()
{
 int x;
 struct node* newnode,*temp;
 temp=head;
    newnode=(struct node*)malloc(sizeof(struct node*)); 
    
    printf("\nEnter element\n");
    scanf("%d",&x);
    newnode->data=x;
    if(head==NULL)
    {
     
     head=newnode;
     newnode->next=NULL;
 }
    else
 {
        while(temp->next!=NULL)
  temp=temp->next;
  temp->next=newnode;
  newnode->next=NULL; 
 }
 print();
}

void print()
{
 struct node* temp;
 temp=head;
 if(head==NULL)
 printf("list is empty !!!\n\n");
 else
 {
 
  printf("\nLIST elements are\t");
  while(temp!=NULL)
  {
   printf("%d\t",temp->data);
   temp=temp->next;
  }
 }
}


OUTPUT

Insert at End Output

Labels: ,