Wednesday, 8 February 2017

C Program To Create a Singly Linked List

#include <stdio.h>

#include <stdlib.h>

struct node{

    int data;

    struct node *next;

}*root=NULL,*newnode;

void insert(int item);

void print();

int main()

{

       int ch,item;

       do

      {

              printf("\nEnter the element to be insert in the linked list: ");

              scanf("%d",&item);

              insert(item);

              printf("\nDo you want to continue ?? [1/0]: ");

              scanf("%d",&ch);

       }while(ch==1); 



       printf("\nThe created linked list is:\n");

       print();

    

       return 0;

}

void insert(int item)

{

       if(root==NULL)

       {

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

              newnode->data=item;

              newnode->next=NULL;

              root=newnode;

       }

       else

       {

              newnode->next=(struct node*)malloc(sizeof(struct node));

              newnode=newnode->next;

              newnode->data=item;

              newnode->next=NULL;

       }

}

void print()

{

      struct node *current;

      current=root;

      while(current!=NULL)

      {

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

            current=current->next;

      }
}
 
 







EmoticonEmoticon