Sunday 28 June 2020

Link List vs Array

Q :Define array and link list. Give one example for each showing its usage


Answer :


Define Link List

struct node
{
     int data;
     struct node *next;
}
int ar[5];

Define Array

int ar[5];

Example array : Input & print 10 numbers

void main()
{
     clrscr();
     int ar[5],i;
     for (i = 1; i < 5; i++)
     {
           printf("Enter no.> ");
           scanf("%d", &ar[i]);
     }
     for (i = 1; i < 5; i++)
           printf("\t%d", ar[i]);
     getch();
}

Example Link List : Numbers input and print but quantity of numbers user will give.

struct node
{
     int data;
     struct node *next;
}
void main()
{
     clrscr();
     int i,j,n;
     struct node *start = NULL,*nw,*pt;
     printf("How many record you want>> ");
     scanf("%d",&i);
     for(j=1;j<=i;j++)
     {
           printf("Enter number>> ");
           scanf("%d",&n);     
           nw = (node*)malloc(sizeof(node));
           nw->data = n;
           nw->next = NULL;
           if (*start == NULL)
           {
                *start = nw;
           }
           else
           {
                nw->next = *start;
                *start = nw;
           }
     }
     /* print*/
     node *pt;
     for (pt = start; pt != NULL; pt = pt->next)

           printf("[ %d ]", pt->data);
     getch();
}


No comments:

Post a Comment