adsense

Hii, welcome to my site. My name is Om prakash kartik. This blog helps you to learn programming languages concepts.

Program in C to implement singly linked list insert data and display data.

Program in C to implement singly linked list insert data and display data.



First Method
#include<stdio.h>
#include<stdlib.h>
  struct Node{
    int data;
    struct Node *next;
  }*start=NULL;
  typedef struct Node Node;
  void insert(int d);
  void show();

  int main()
   {
       insert(4);
       insert(85);
       insert(135);
       insert(35);
       insert(10);
       printf("Elements of linked list is ");
       show();
       return 0;
   }
   void insert(int d)
    {
     Node *temp,*ptr;
     temp=(Node*)malloc(sizeof(Node));
     temp->data=d;
     temp->next=NULL;
     if(start==NULL)
      {
       start=temp;
   }
   else
    {
     ptr=start;
     while(ptr->next!=NULL)
         ptr=ptr->next;
         ptr->next=temp;
    }
 }

 void show()
  {
   Node *temp;
   if(start==NULL)
    {
     printf("Linked list is empty.");
    }
   else
    {
     temp=start;
     while(temp!=NULL)
      {
       printf("%5d",temp->data);
       temp=temp->next;
      }
    }
  }
Second Method
#include<stdio.h>
#include<stdlib.h>
  struct Node{
    int data;
    struct Node *next;
  };
  typedef struct Node Node;
  Node *head=NULL,*tail=NULL;
  void insert(int d);
  void show();

  int main()
   {
       insert(4);
       insert(85);
       insert(135);
       insert(35);
       insert(10);
       insert(24);
       insert(87);
       printf("Elements of linked list is ");
       show();
       return 0;
   }
   void insert(int d)
    {
     Node *newN,*ptr;
     newN=(Node*)malloc(sizeof(Node));
     newN->data=d;
     newN->next=NULL;
        if(head==NULL){
          head=newN;
          tail=newN;
       }
       else{
         tail->next=newN;
         tail=newN;
       }
     }

 void show()
  {
   Node *temp;
   if(head==NULL)
    {
     printf("Linked list is empty.");
    }
   else
    {
     temp=head;
     while(temp!=NULL)
      {
       printf("%5d",temp->data);
       temp=temp->next;
      }
    }
  }
Output :-








Post a Comment

0 Comments