Linked List implementation in C

Linked List is a linear data structure and the elements are linked using pointers,They can be used to implement several other common abstract data types: stacks, queues, associative arrays though it is not uncommon to implement the other data structures directly without using a list as the basis of implementation.

 Here in this code we will add new data in the linked list and the user will be asked "Do you want to add more node>" if user press “n”  then the all the elements will be printed .

      HEAD    

       |

       |

   *********     *********       *************

   | 11 | o----->|  13  | o----->| 15 | NULL |

   *********     *********       *************  

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node//representing node using structure
{
int data;//data
struct node *next;//pointer to the next node
}*beg=NULL;

void linkcreate()
{
char ch;
 do
 {
  struct node *new_node,*current;

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

  printf("nEnter the element : ");
  scanf("%d",&new_node->data);
  new_node->next=NULL;

  if(beg==NULL)
  {
  beg=new_node;
  current=new_node;
  }
  else
  {
  current->next=new_node;
  current=new_node;
  }

 printf("nDo you want to add more node? : ");
 ch=getche();
 }while(ch!='n');
}
//function that displays the elements
void display()
{
struct node *new_node;
 printf("The Linked List is: n");
 new_node=beg;
 while(new_node!=NULL)
   {
   printf("%d--->",new_node->data);
   new_node=new_node->next;
   }
  printf("NULL");
}

void main()
{
linkcreate();
display();
}

OUTPUT:
Enter the element :11
Do you want to add more node?:y
Enter the element: 13
Do you want to add more node?: y
Enter the element: 15 Do you want to add more node? : n
The Linked List is: 11--->13--->15--->NULL

Leave a Reply

Your email address will not be published. Required fields are marked *