Tuesday, October 1, 2013

Linked List Program in C


/*
LinkedList.c: this program is implementation of LinkedList in C. 

Date: 02/10/2013. 

*/


#include<stdio.h>
#include<string.h> 

void CreateNode(); 
void InsertElements(); 
void DisplayElements();
void DeleteElement(int a);

typedef struct 
{
 int data; 
 struct Node *next; 
}Node;

typedef Node *List;
List head,tail,temp; 

int main()
{
 int choice,data;  
 temp =NULL; head =NULL ; tail =head; 
 while(1){
 printf("==Linked List Menu==\n1.Insert Element\n2.Display\n3.Delete\n4.Exit\n");
 scanf("%d",&choice); 
 switch(choice)
 {
 case 1:
  InsertElements(); 
  break; 
 case 2:
  DisplayElements();
  break;
 case 3:
  printf("Enter the number that you want to delete\n");  
  scanf("%d",&data);
  DeleteElement(data); break; 
 default:
  printf("Thanks for using My programming ..\n");
  exit(0); 
 }
 }// end of infinite loop  


 return 0; 
}

void CreateNode()
{

 int data; 
 printf("Enter your element\n"); 
 scanf("%d",&data);
 temp = (List)malloc(sizeof(Node)); 
 temp->data = data; 
 temp->next =NULL; 
 
} 
void InsertElements()
{
 CreateNode(); 
 if(head == NULL)
 {
  head = temp; 
  tail =head; 
 }
 else 
 {
  tail->next = temp; 
  tail = tail->next;  
 }
}
void DisplayElements()
{
 if(head!=NULL)
 {
  printf("Elements===>\n");
 for(temp =head; temp!= NULL ; temp = temp->next)
  {
   printf("%d\t",temp->data);
  }
  printf("\n");
 }
 else
 {
  printf("Your Linked List Empty\n");
 }
}

void DeleteElement(int a)
{
 if(head!=NULL)
 {
  if(head->data == a)
  {
   head = head->next;
  }
  else{
   tail = head; 
   temp = head->next; 
   int found =0; 
  while(temp !=NULL)
   {
    if(temp->data ==a)
     {
     tail->next = temp->next;
 
          printf("element is found\\deleted\nPlease use option 2 to see remaining");
     found =1;     
     break;  
            }  
     else
     {
      tail = temp; 
      temp = temp->next;  
            }   
   }
   if(!found)
   printf("element is not present\n");   
      
      }
  
 
 }
 else
 {
  printf("Your Linked List Empty\n");
 }
}

No comments:

Post a Comment