Wednesday, February 15, 2017

The Linked Lists !!!

Hello there! Today you will learn about inserting the elements in to the linked lists.
But before we begin let me tell you something about he linked list. In arrays we have to first declare the size of the array. After declaring the array we cannot increase its size and further elements in array are arranged in linear fashion or one after the another. But in case of linked list this is not the case. Here you can expand or shrink the size of the linked list as per your requirement so there is no wastage and excess of storage also elements are arranged non linearly.  A Node in the linked list  has the following two parts:

          1) Data Field
          2) Address Field.

Data field stores the data in the node while address field stores the address of the next node.

Now its time to introduce you the basic terminologies.

malloc(): Malloc function is used to allocated/reserve the memory for the next element you are going to add in the linked list. Insertion of the next element in the linked list is done as:

Node *a : (Node *)malloc(sizeof (Node));
Here we have allocated the space for node a.

Now let us begin.

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node      
/*Defining the node*/
{
int data;               
 /*Declaring Nodes data part*/
struct node *next;       
/*Declaring Node's next address part*/
}Node;
void main()
{
clrscr();
Node *a=(Node *)malloc(sizeof (Node)); 
/* Allocates space for node A*/
a->next = NULL;
Node *first = a;
/* Here I used another pointer to the first Node*/
int count = 0;
while(count<100)    
{
int choice;
printf("enter choice 1)insert 2)exit");
/* User has to enter 1 to insert the element 2 to exit*/
scanf("%d",&choice);
if(choice==1)
{
printf("enter the data");
scanf("%d",&a->data);
 /* Scan and store the data in the data field of Node a*/
a->next = (Node *)malloc(sizeof (Node));
/* Allocate space for the next Node */
a=a->next; 
/*Update A by the next Node */
a->data=NULL; 
/* Put data part of Node A as null */
count++; 
}
else if(choice !=1)
break;  
 /* If user doesn't enter 1 than exit */
}
a = first; 
 /* initialize a by the first node */
while(a->data!=NULL)   
/* Continue until the data part of a becomes Null */
{
printf("%d ",a->data); 
/* Print data field of a*/
a = a->next; 
/* Update a by next node */
}
a =first; 
getch();

}



Hope that you enjoyed reading this blog. I will cover other operations in the linked list(insertion at beginning , insertion in middle, deletion etc.) in the next blog. Stay tuned, Stay programmed.

No comments:

Post a Comment