AdrianMadajewski

Linked List 1

Nov 4th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h> // for malloc(), free()
  3.  
  4. typedef struct Node {
  5.     int data;
  6.     struct Node *next;
  7. } Node_t;
  8.  
  9. typedef int bool_t;
  10.  
  11. //  TODO:
  12. /// Handle case exceptions when HEAD is empty in pop(), push()
  13. //  Add boolean isEmpty()
  14. //  Add function: clear() which clears the linked list (leaves nothing, and cleans up memory)
  15. //  Add function: length() which returns how many element does the list possess
  16. //  Add function: addMany(@param array) which adds elements of the array (or another linked list)
  17. //  ...
  18.  
  19. bool_t isEmpty(Node_t *node) {
  20.     return node == NULL;
  21. }
  22.  
  23. Node_t *createNode(int data, Node_t *next_node) {
  24.     Node_t *node = (Node_t *)malloc(sizeof(Node_t));;
  25.     node->data = data;
  26.     node->next = next_node;
  27. }
  28.  
  29. void push(Node_t *head, int data) {
  30.     Node_t *new_node = createNode(data, NULL);
  31.     Node_t *it = head;
  32.     while (it->next != NULL) {
  33.         it = it->next;
  34.     }
  35.     it->next = new_node;
  36. }
  37.  
  38. void printList(Node_t *head) {
  39.     Node_t *it = head;
  40.     while (!isEmpty(it)) {
  41.         printf("%d->", it->data);
  42.         it = it->next;
  43.     }
  44.     printf("\n");
  45. }
  46.  
  47. int pop(Node_t *head) {
  48.     int ret;
  49.  
  50.     // Handle case if HEAD has only 1 element
  51.     if (head->next == NULL) {
  52.         ret = head->data;
  53.         free(head);
  54.         return ret;
  55.     }
  56.  
  57.     Node_t *it = head;
  58.     while (it->next->next != NULL) {
  59.         it = it->next;
  60.     }
  61.     ret = it->next->data;
  62.     free(it->next);
  63.     it->next = NULL;
  64.     return ret;
  65. }
  66.  
  67. int main(void) {
  68.     Node_t *HEAD = createNode(10, NULL);
  69.     push(HEAD, 20);
  70.     push(HEAD, 3);
  71.     printList(HEAD);
  72.     // prints: 10->20->3
  73.  
  74.     pop(HEAD); // pops 3
  75.     printList(HEAD); // prints: 10->20
  76.    
  77.     return 0;
  78. }
Add Comment
Please, Sign In to add comment