Wednesday, 23 May 2012

Linked List in C Programming

#include<stdio.h>
#include<conio.h>
#define null 0

//structure of a node
struct n
{
 int data;        //data to store
 struct n *next;  //pointer to next node
};

typedef struct n node;
node *first, *p, *last;

void create(node*, int);
void display(node*, int);
void sort(node*);
int search(node*, int, int);
void Delete(node *,int);

void main()
{
 int count,d;

 clrscr();

 printf("Enter number of nodes: ");
 scanf("%d",&count);

 //creating nodes
 if(count>0)
 {
  first = (node *)malloc(sizeof(node));
  printf("Enter Data : ");
  scanf("%d",&first->data);
  first->next=null;

  count--;

  create(first,count);
 }

 printf("Displaying node contents -- \n\n\n");
 display(first,1);

 //sort operation on linked list
 sort(first);
 printf("\n\n\nAfter Sorting: \n\n");
 display(first,1);

 //search position of specified data
 printf("\n\n\nEnter data to search : ");
 scanf("%d",&d);

 count = search(first,d,1);

 if(count!=-1)
 {
     printf("Data found at %d.",count);
 }
 else
  printf("Data not found");

 //Add more nodes
 printf("\n\n\nEnter more number of nodes to add: ");
 scanf("%d",&count);

 create(last,count);
 sort(first);

 printf("\n\n\nFinal node values:");
 display(first,1);

 //Deleting a node
 printf("\n\nEnter data to delete: ");
 scanf("%d",&d);

 Delete(first,d);

 printf("\n\nAfter deletion nodes:\n ");
 display(first,1);

 getch();
}

void create(node *p,int count)
{
 if(count>0)
 {
  p->next =  (node *)malloc(sizeof(node));
  last=p=p->next;

  printf("Enter Data: ");
  scanf("%d",&p->data);
  p->next = null;

  count--;
  create(p,count);
 }
 else
  return;
}

void display(node *p, int count)
{
     if(p!=null)
     {
 printf("\nNode %d: %d",count,p->data);
 count++;
 display(p->next,count);
     }
     else
 return;
}

int search(node *p,int data, int count)
{
 if(p!=null)
 {
  if(data==p->data)
   return count;
  else
  {
   count++;
   search(p->next,data,count);
  }
 }
 else
  return -1;  //no matching node found
}

void Delete(node *p,int data)
{
 int count = search(first,data,1);

 if(count<0)
  printf("Data not found.");
 else
 {       p=first;
  count--;

  if(count==0)
   first=first->next;
  else
  {
   while(count>1)
   {
      p=p->next;
      count--;
   }

   p->next=p->next->next;
  }
 }
}

void sort(node *p)
{
 while(p!=null)
 {
  node *q = p->next;

  while(q!=null)
  {
   if(q->data<p->data)
   {
    int temp;
    temp=p->data;
    p->data=q->data;
    q->data=temp;
   }

   q=q->next;
  }
  p=p->next;
 }
}

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.

Do you like this article?