Xisepe

List merge

Apr 7th, 2022
60
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 1 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3.  
  4. typedef struct List {
  5.     int val;
  6.     struct List *next;
  7. } List;
  8.  
  9. void add(List **head, const int val) {
  10.     if (*head == NULL) {
  11.         *head = (List *) malloc(sizeof(List));
  12.         (*head)->next = NULL;
  13.         (*head)->val = val;
  14.         return;
  15.     }
  16.     List *current = *head;
  17.     while (current->next) {
  18.         current = current->next;
  19.     }
  20.     current->next = (List *) malloc(sizeof(List));
  21.     current->next->next = NULL;
  22.     current->next->val = val;
  23. }
  24.  
  25. List *merge(List *l1, List *l2) {
  26.     if (l1 == NULL || l2 == NULL)
  27.         return l2;
  28.     List *l1_t = l1;
  29.     List *l2_t = l2;
  30.     List *head = NULL;
  31.     List *cur = (List *) malloc(sizeof(List));
  32.     cur->next = NULL;
  33.     while (l1_t || l2_t) {
  34.         const int v1 = l1_t == NULL ? INT_MAX : l1_t->val;
  35.         const int v2 = l2_t == NULL ? INT_MAX : l2_t->val;
  36.         if (v1 <= v2) {
  37.             if (!head)
  38.                 head = l1_t;
  39.             cur->next = l1_t;
  40.             l1_t = l1_t->next;
  41.             cur = cur->next;
  42.         } else {
  43.             if (!head)
  44.                 head = l2_t;
  45.             cur->next = l2_t;
  46.             l2_t = l2_t->next;
  47.             cur = cur->next;
  48.         }
  49.     }
  50.  
  51.     return head;
  52. }
  53.  
  54. void print(List *head) {
  55.     List *current = head;
  56.     while (current) {
  57.         printf("%d ", current->val);
  58.         current = current->next;
  59.     }
  60. }
  61.  
  62. int main() {
  63.     List *f = NULL;
  64.     List *t = NULL;
  65.  
  66.     add(&f, -11);
  67.     add(&f, 1);
  68.     add(&f, 5);
  69.  
  70.     add(&t, -40);
  71.     add(&t, 2);
  72.     add(&t, 4);
  73.     add(&t, 6);
  74.  
  75.     List *r = merge(f, t);
  76.     print(r);
  77.  
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment