Advertisement
kebria

Deleting the first node of a single linked list

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