Insert a Node at the Beginning of the single link list program in C using switch -Studyinight Programmer

#include<stdio.h>

#include<stdlib.h>

void addbegin();

void display();

struct node

{

    int data;

    struct node* next;

};

root=NULL;

void addbegin()

{

    struct node* temp;

temp=(struct node*)malloc(sizeof(struct node));

printf("Enter node data to add begin\n");

scanf("%d",&temp->data);

temp->next=NULL;

if(root==NULL)

    root=temp;

else

{

    temp->next=root;

    root=temp;

}

}

void display()

{

  struct node * temp;

  temp=root;

  if(temp==NULL)

        printf("List is Empty\n");

  else

  {

      while(temp!=NULL)

      {

          printf("%d-->",temp->data);

          temp=temp->next;

      }

      printf("NULL\n");

  }

}

int main()

{

    int ch;

    while(1)

    {

        printf("1.Insert element at begin\n");

        printf("2.Display element\n");

        printf("3.exit\n");

        printf("Enter your choice\n");

        scanf("%d",&ch);

        switch(ch)

        {

        case 1:

            addbegin();

            break;

        case 2:

            display();

            break;

        case 3:

            exit(1);

        default:

            printf("Please enter right choice\n");

        }

    }

}

Post a Comment

0 Comments