Wednesday, 20 September 2017

Single link list upto 20 number

Q : Write a program to create a link list. There should be 20 nodes in the list, each node contains an integer between 1-20. The list should be printed at the end.


Solution : 

#include<stdio.h>
typedef struct nlist
{
     int data;
     struct nlist *next;
}node;
node *start=NULL;
node* create(int);
void add(int);

int input();
void print();
void main()
{
     int opt,i;
     for(i=1;i<=20;i++)
     {
          printf("Enter %d position number>> ",i);
          add(input());
     }
     print();
    
}
node* create(int n)
{
     node *nw;
     nw=(node*) malloc(sizeof(node));
     nw->data=n;
     nw->next=NULL;
     return nw;
}
void add(int n)
{
     node *nw,*pt;
     nw=create(n);
     if(start==NULL)
          start=nw; /* First Element */
     else
     {
          for(pt=start;pt->next!=NULL;pt=pt->next)
          {
          }
          pt->next=nw;
     }
}
int input()
{
     int n;
     do
     {

          scanf("%d",&n);
          if(n>20)
              printf("\nInput in range of 1-20\n");
     }while(n>20);
     return n;
}
void print()
{
     node *pt;
     for(pt=start;pt!=NULL;pt=pt->next)
          printf("[%d] ",pt->data);

No comments:

Post a Comment