Insertion at Beginning In Single Linked List Using C

Description

 This program is used to insert elements at the beginning 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 insbeg();
void print();

void main()
{
  int choice;
  do
  {
   printf("\n__MENU__\n1.Insert at the beginning\n2...EXIT...\n");
   printf("\nENTER your choice\n");
   scanf("%d",&choice);
   switch(choice)
   {
    case 1 :insbeg();break;
    case 2:printf("~~~~~~~THANK YOU~~~~~~~\n");break;
   default:printf("INVALID input !!!");break;   
  }
  }while(choice!=2);
}
void insbeg()
{
 int x;
 struct node* newnode,*temp;
 temp=head;
    newnode=(struct node*)malloc(sizeof(struct node*)); 
    printf("Enter element\n");
    scanf("%d",&x);
 newnode->data=x;
 if(head==NULL)
 {
  head=newnode;
  newnode->next=NULL;
 }
 else
 {
  newnode->next=temp;
  head=newnode;
 }
  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 beginning Output1 Insert at beginning Output2

Labels: ,