Advertisement
BenTibnam

Singly Linked List in C

Jul 19th, 2023 (edited)
824
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.01 KB | Software | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node
  5. {
  6.     char *data;
  7.     struct node *next;
  8. }
  9. node;
  10.  
  11. int main (void)
  12. {
  13.     node *list = NULL;
  14.  
  15.     // adding the first node
  16.     node *n =  malloc(sizeof(node));
  17.     n->data = "First Node";
  18.     n->next = NULL;
  19.     list = n;
  20.  
  21.     // adding the second node
  22.     n = malloc(sizeof(node));
  23.     n->data = "Second Node";
  24.     n->next = list;
  25.     list = n;
  26.  
  27.     // adding the third node
  28.     n = malloc(sizeof(node));
  29.     n->data = "Third Node";
  30.     n->next = list;
  31.     list = n;
  32.  
  33.     // printing the linked list data
  34.     node *current_node = list;
  35.     while (current_node != NULL)
  36.     {
  37.         printf("Current node data: %s\n", current_node->data);
  38.         current_node = current_node->next;
  39.     }
  40.  
  41.     // freeing the memory after done with list
  42.     current_node = list;
  43.     while (current_node != NULL)
  44.     {
  45.         node *next_node = current_node->next;
  46.         free(current_node);
  47.         current_node = next_node;
  48.     }
  49.  
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement