Moortiii

Linked List - C

Sep 5th, 2018
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.02 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3.  
  4. typedef struct Node {
  5.     int data;
  6.     struct Node* next;
  7. } Node;
  8.  
  9. typedef struct Linked_List {
  10.     Node* root;
  11. } Linked_List;
  12.  
  13. Node* create_node(int number) {
  14.     Node* node = (Node*)malloc(sizeof(Node));
  15.     node->data = number;
  16.     node->next = NULL;
  17.     return node;
  18. }
  19.  
  20. Linked_List* create_list() {
  21.     Linked_List* list = (Linked_List*)malloc(sizeof(Linked_List));
  22.     list->root = NULL;
  23. }
  24.  
  25. void add_first(Linked_List* list, Node* node) {
  26.     if(list->root == NULL) {
  27.         list->root = node;
  28.     } else {
  29.         Node* temp = list->root;
  30.         list->root = node;
  31.         list->root->next = temp;
  32.     }
  33. }
  34.  
  35. void add_last(Linked_List* list, Node* node) {
  36.     if(list->root == NULL) {
  37.         list->root = node;
  38.     } else {
  39.         Node* iterator = list->root;
  40.         while(iterator->next != NULL) {
  41.             iterator = iterator->next;
  42.         }
  43.         iterator->next = node;
  44.     }
  45. }
  46.  
  47. void print_list(Linked_List* list) {
  48.     Node* node = list->root;
  49.     while(node != NULL) {
  50.         printf("Number: %i\n", node->data);
  51.         node = node->next;
  52.     }
  53.     printf("\n");
  54. }
  55.  
  56. Node* remove_and_retrieve_first(Linked_List *list) {
  57.     if(list->root == NULL) {
  58.         printf("Tried to return value from empty list, returned NULL");
  59.         return NULL;
  60.     } else {
  61.         Node* temp = list->root;
  62.         list->root = list->root->next;
  63.         return temp;
  64.     }
  65. }
  66.  
  67. Node* remove_and_retrieve_last(Linked_List* list) {
  68.     if(list->root == NULL) {
  69.         printf("Tried to return value from empty list, returned NULL");
  70.         return NULL;
  71.     } else {
  72.         Node* node = list->root;
  73.         while(node->next->next != NULL) {
  74.             node = node->next;
  75.         }
  76.  
  77.         Node* temp = node;
  78.         node->next = NULL;
  79.         return temp;
  80.     }
  81. }
  82.  
  83. int main() {
  84.     Linked_List* list = create_list();
  85.  
  86.     for(int i = 0; i <= 10000; i += 5)
  87.         add_last(list, create_node(i));
  88.  
  89.     print_list(list);
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment