Advertisement
kebria

Deleting the node at particular position (single linked list)

Jun 15th, 2021 (edited)
554
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | None | 0 0
  1. /* Deleting the node at particular position */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. struct node {
  5.     int data;
  6.     struct node* link;
  7. };
  8. void del_pos(struct node** head, int position)
  9. {
  10.     struct node* current = *head;
  11.     struct node* previous = *head;
  12.     if (*head == NULL)
  13.         printf("List is already empty\n");
  14.     else if (position == 1)
  15.     {
  16.         *head = current->link;
  17.         free(current);
  18.         current = NULL;
  19.     }
  20.     else
  21.     {
  22.         while (position != 1)
  23.         {
  24.             previous = current;
  25.             current = current->link;
  26.             position--;
  27.         }
  28.         previous->link = current->link;
  29.         free(current);
  30.         current = NULL;
  31.     }
  32. }
  33. int main()
  34. {
  35.     struct node* head = NULL;
  36.     head = malloc(sizeof(struct node));
  37.     head->data = 45;
  38.     head->link = NULL;
  39.     struct node* current = NULL;
  40.     current = malloc(sizeof(struct node));
  41.     current->data = 90;
  42.     current->link = NULL;
  43.     head->link = current;
  44.     struct node* third = NULL;
  45.     third = malloc(sizeof(struct node));
  46.     third->data = 98;
  47.     third->link = NULL;
  48.     head->link->link = third;
  49.     printf("Before Deleting: ");
  50.     printf("%d %d %d\n", head->data, current->data, third->data);
  51.     struct node* ptr;
  52.     int position = 2;
  53.     del_pos(&head, position);
  54.     ptr = head;
  55.     printf("After deleting: ");
  56.     while (ptr != NULL)
  57.     {
  58.         printf("%d ", ptr->data);
  59.         ptr = ptr->link;
  60.     }
  61.     return 0;
  62. }
  63.  
  64.  
  65. /*
  66. Output:
  67. Before Deleting : 45 90 98
  68. After deleting : 45 98
  69. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement