Advertisement
DMG

Singly linked list in C

DMG
Dec 17th, 2014
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.03 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. typedef struct Node ListNode;
  5.  
  6. struct Node {
  7.        int element;
  8.        ListNode *next;
  9. };
  10.  
  11. void initialize_list (ListNode **head) {
  12.      *head = NULL;
  13. }
  14.  
  15. void add_element (ListNode **head, int element_data) {
  16.      ListNode *new_node;
  17.      new_node = (ListNode *)malloc(sizeof(ListNode));
  18.      new_node -> element = element_data;
  19.      new_node -> next = NULL;
  20.      
  21.      if (*head == NULL) {
  22.         *head = new_node;
  23.         return;
  24.      }
  25.      
  26.      ListNode *current;
  27.      current = *head;
  28.      
  29.      while (current -> next != NULL) {
  30.            current = current -> next;
  31.      }
  32.      
  33.      current -> next = new_node;
  34. }
  35.  
  36. void delete_element (ListNode **head, int element_data) {
  37.      ListNode *current;
  38.      ListNode *previous;
  39.      
  40.      previous = *head;
  41.      current = *head;
  42.      
  43.      while (current != NULL) {
  44.            if (current -> element == element_data) {
  45.                    if (previous != current) {
  46.                        previous -> next = current -> next;
  47.                    }
  48.                    else {
  49.                        *head = current -> next;
  50.                    }
  51.                    
  52.                    free(current);
  53.                    return;
  54.            }
  55.            
  56.            previous = current;
  57.            current = current -> next;
  58.      }
  59. }
  60.  
  61. void print_list (ListNode **head) {
  62.      ListNode *current;
  63.      current = *head;
  64.      
  65.      int i = 0;
  66.      
  67.      while (current != NULL) {
  68.            printf("Singly_linked_list[%d] == %d \n", i, current -> element);
  69.            ++i;
  70.            current = current -> next;
  71.      }
  72.      
  73.      printf("\n");
  74. }
  75.  
  76. int main()
  77. {
  78.     ListNode *head;
  79.     initialize_list(&head);
  80.  
  81.     add_element(&head, 23);
  82.     add_element(&head, 4);
  83.     add_element(&head, 1);
  84.  
  85.     print_list(&head);
  86.  
  87.     delete_element(&head, 1);
  88.  
  89.     print_list(&head);
  90.    
  91.     add_element(&head, 7);
  92.     add_element(&head, 2);
  93.    
  94.     print_list(&head);
  95.  
  96.     system("PAUSE");
  97.     return 0;  
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement