Advertisement
AquaBlitz11

Linked List - Recursive

Oct 12th, 2018
371
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node {
  5.     int key;
  6.     struct Node *next;
  7. } Node;
  8.  
  9. Node *create_node(int key, Node *next=nullptr) {
  10.     Node *ptr = (Node*)malloc(sizeof(Node));
  11.     ptr->key = key;
  12.     ptr->next = next;
  13.     return ptr;
  14. }
  15.  
  16. Node *push_front(Node *head, int key) {
  17.     return create_node(key, head);
  18. }
  19.  
  20. Node *push_back(Node *head, int key) {
  21.     if (!head)
  22.         return create_node(key);
  23.     head->next = push_back(head->next, key);
  24.     return head;
  25. }
  26.  
  27. Node *insert_in_order(Node *head, int key) {
  28.     if (!head)
  29.         return create_node(key);
  30.     if (head->key >= key)
  31.         return create_node(key, head);
  32.     head->next = insert_in_order(head->next, key);
  33.     return head;
  34. }
  35.  
  36. Node *find_key(Node *head, int key) {
  37.     if (!head)
  38.         return nullptr;
  39.     if (head->key == key)
  40.         return head;
  41.     return find_key(head->next, key);
  42. }
  43.  
  44. Node *delete_key(Node *head, int key) {
  45.     if (!head)
  46.         return nullptr;
  47.     if (head->key == key) {
  48.         Node *tmp = head->next;
  49.         free(head);
  50.         return tmp;
  51.     } else {
  52.         head->next = delete_key(head->next, key);
  53.         return head;
  54.     }
  55. }
  56.  
  57. void print_list(Node *head) {
  58.     if (!head)
  59.         printf("NULL\n");
  60.     else {
  61.         printf("%d -> ", head->key);
  62.         print_list(head->next);
  63.     }
  64. }
  65.  
  66. Node *free_list(Node *head) {
  67.     if (head) {
  68.         free_list(head->next);
  69.         free(head);
  70.     }
  71.     return nullptr;
  72. }
  73.  
  74. int main()
  75. {
  76.     Node *p = nullptr, *head = nullptr;
  77.     head = insert_in_order(head, 10);
  78.     head = insert_in_order(head, 20);
  79.     head = insert_in_order(head, 30);
  80.     print_list(head);
  81.     p = find_key(head, 50);
  82.     print_list(p);
  83.     p = find_key(head, 30);
  84.     print_list(p);
  85.     p = find_key(head, 20);
  86.     print_list(p);
  87.     head = delete_key(head,50);
  88.     head = delete_key(head,20);
  89.     print_list(head);
  90.     head = free_list(head);
  91.     print_list(head);
  92.  
  93.     return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement