Linked list |C program to implement insertion, deletion and displaying using|

 C program to implement insertion, deletion and displaying using Linked list

Code:

#include <stdio.h>
#include <stdlib.h>
struct node
{
  int data;
  struct node *link;
};
struct node *head_node, *first_node, *temp_node = 0, *prev_node;
void insert();
void display();
void del();
int count();
int x;
void main()
{
  int option;
  while (1)
  {
    printf("\nOperations\n");
    printf("1. Insert into Linked List \n");
    printf("2. Delete from Linked List \n");
    printf("3. Display Linked List\n");
    printf("4. Count Linked List\n");
    printf("5. Exit\n");
    printf("\nchoose option: ");
    scanf("%d", &option);
    switch (option)
    {
      case 1:
insert();
break;
      case 2:
del();
break;
      case 3:
display();
break;
      case 4:
count();
break;
      case 5:
exit(0);
      default:
printf("\nEnter the correct option\n");
break;
    }
  }
}

void insert()
{
  printf("\nEnter Element to be inserted : ");
  scanf("%d", &x);
  temp_node = (struct node *) malloc(sizeof (struct node));
  temp_node->data = x;
  if (first_node == 0)
  {
    first_node = temp_node;
  }
  else
  {
    head_node->link = temp_node;
  }
  temp_node->link = 0;
  head_node = temp_node;
  fflush(stdin);
}
void del()
{
  int countvalue, pos, i = 0;
  countvalue = count();
  temp_node = first_node;
  printf("\nEnter Position of the element to delete : ");
  scanf("%d", &pos);
  if (pos > 0 && pos <= countvalue)
  {
    if (pos == 1) 
   {
      temp_node = temp_node -> link;
      first_node = temp_node;
      printf("\nDeleted Successfully \n\n");
   }
  else
  {
      while (temp_node != 0)
      {
if (i == (pos - 1))
{
  prev_node->link = temp_node->link;
  if(i == (countvalue - 1))
  {
     head_node = prev_node;
  }
  printf("\nDeleted Successfully \n\n");
  break;
}
else
       {
  i++;
  prev_node = temp_node;
  temp_node = temp_node -> link;
}
      }
    }
  }
  else
    printf("\nInvalid Position \n\n");
}
void display()
{
  temp_node = first_node;
  printf("\nContents of Linked List : \n");
  while (temp_node != 0)
  {
    printf("| %d |  ", temp_node->data);
    temp_node = temp_node -> link;
  }
}
int count()
{
  int count = 0;
  temp_node = first_node;
  while (temp_node != 0)
  {
    count++;
    temp_node = temp_node -> link;
  }
  printf("\nNo of Items in the Linked List : %d\n", count);
  return count;
}

Output:



Explanation:

  • The first is we are declaring the nodes like temp, head, prev etc,.
  • We are using switch statement to enter the choices.
  • we are going to insert , delete, and display .









Comments

Popular posts from this blog

Use of Backslash "\n" in C language

COHESION AND COUPLING material

Coding and Testing in software engineering