Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <malloc.h>
- typedef struct List {
- int val;
- struct List *next;
- } List;
- void add(List **head, const int val) {
- if (*head == NULL) {
- *head = (List *) malloc(sizeof(List));
- (*head)->next = NULL;
- (*head)->val = val;
- return;
- }
- List *current = *head;
- while (current->next) {
- current = current->next;
- }
- current->next = (List *) malloc(sizeof(List));
- current->next->next = NULL;
- current->next->val = val;
- }
- List *merge(List *l1, List *l2) {
- if (l1 == NULL || l2 == NULL)
- return l2;
- List *l1_t = l1;
- List *l2_t = l2;
- List *head = NULL;
- List *cur = (List *) malloc(sizeof(List));
- cur->next = NULL;
- while (l1_t || l2_t) {
- const int v1 = l1_t == NULL ? INT_MAX : l1_t->val;
- const int v2 = l2_t == NULL ? INT_MAX : l2_t->val;
- if (v1 <= v2) {
- if (!head)
- head = l1_t;
- cur->next = l1_t;
- l1_t = l1_t->next;
- cur = cur->next;
- } else {
- if (!head)
- head = l2_t;
- cur->next = l2_t;
- l2_t = l2_t->next;
- cur = cur->next;
- }
- }
- return head;
- }
- void print(List *head) {
- List *current = head;
- while (current) {
- printf("%d ", current->val);
- current = current->next;
- }
- }
- int main() {
- List *f = NULL;
- List *t = NULL;
- add(&f, -11);
- add(&f, 1);
- add(&f, 5);
- add(&t, -40);
- add(&t, 2);
- add(&t, 4);
- add(&t, 6);
- List *r = merge(f, t);
- print(r);
- }
Advertisement
Add Comment
Please, Sign In to add comment