Advertisement
STANAANDREY

intercl lists

Feb 13th, 2023
920
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.56 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node {
  5.   int x;
  6.   struct Node *nxt;
  7. } Node;
  8.  
  9. Node *mkNode(int x, Node *nxt) {
  10.   Node *node = malloc(sizeof(Node));
  11.   if (node == NULL) {
  12.     perror("");
  13.     exit(-1);
  14.   }
  15.   node->x = x;
  16.   node->nxt = nxt;
  17.   return node;
  18. }
  19.  
  20. Node *addEnd(Node *node, int x) {
  21.   if (!node) {
  22.     return mkNode(x, NULL);
  23.   }
  24.   Node *p;
  25.   for (p = node; p->nxt; p = p->nxt);
  26.   p->nxt = mkNode(x, NULL);
  27.   return node;
  28. }
  29.  
  30. void printList(Node *node) {
  31.   for (; node; node = node->nxt) {
  32.     printf("%d ", node->x);
  33.   }
  34.   puts("");
  35. }//*/
  36.  
  37. void freeList(Node *node) {
  38.   Node *curr = node, *nxt;
  39.   while (curr) {
  40.     nxt = curr->nxt;
  41.     free(curr);
  42.     curr = nxt;
  43.   }
  44. }
  45.  
  46. Node *readList() {
  47.   int n, x;
  48.   scanf("%d", &n);
  49.   Node *node = NULL;
  50.   for (int i = 0; i < n; i++) {
  51.     scanf("%d", &x);
  52.     node = addEnd(node, x);
  53.   }
  54.   return node;
  55. }
  56.  
  57. Node *intercl(Node *node1, Node *node2) {
  58.   Node *res = NULL;
  59.   while (node1 && node2) {
  60.     if (node1->x < node2->x) {
  61.       res = addEnd(res, node1->x);
  62.       node1 = node1->nxt;
  63.     } else {
  64.       res = addEnd(res, node2->x);
  65.       node2 = node2->nxt;
  66.     }
  67.   }
  68.   while (node1) {
  69.     res = addEnd(res, node1->x);
  70.     node1 = node1->nxt;
  71.   }
  72.   while (node2) {
  73.     res = addEnd(res, node2->x);
  74.     node2 = node2->nxt;
  75.   }
  76.   return res;
  77. }
  78.  
  79. int main(void) {
  80.   Node *node1 = readList();
  81.   Node *node2 = readList();
  82.   Node *res = intercl(node1, node2);
  83.   printList(res);
  84.   freeList(res);
  85.   freeList(node1);
  86.   freeList(node2);
  87.   return 0;
  88. }
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement