#include <stdio.h>
#include <stdlib.h>

struct node {
    int val;
    struct node *next;
};

struct node* createNode(int val) {
    struct node* newNode = (struct node*) malloc(sizeof(struct node));
    newNode->val = val;
    newNode->next = NULL;
    return newNode;
}

void printList(struct node* head) {
    while (head != NULL) {
        printf("%d ", head->val);
        head = head->next;
    }
    printf("\n");
}

struct node* merge(struct node* list1, struct node* list2) {
    struct node* ans = (struct node*) malloc(sizeof(struct node));
    struct node* head = ans;

    while (list1 != NULL && list2 != NULL) {
        if (list1->val < list2->val) {
            ans->next = list1;
            list1 = list1->next;
            ans = ans->next;
        }
        else if (list1->val == list2->val) {
            ans->next = list1;
            ans = ans->next;
            list1 = list1->next;
            list2 = list2->next;
        }
        else {
            ans->next = list2;
            list2 = list2->next;
            ans = ans->next;
        }
    }

    for (; list1; list1 = list1->next) {
        ans->next = list1;
        ans = ans->next;
    }

    for (; list2; list2 = list2->next) {
        ans->next = list2;
        ans = ans->next;
    }

    struct node* temp = head->next; // 跳過 dummy 頭節點
    free(head); // 釋放 dummy node 記憶體
    return temp;
}

int main() {
    // 建立 list1: 1 -> 3 -> 5
    struct node* list1 = createNode(1);
    list1->next = createNode(3);
    list1->next->next = createNode(5);

    // 建立 list2: 2 -> 4 -> 6 -> 8
    struct node* list2 = createNode(2);
    list2->next = createNode(4);
    
    list2->next->next = createNode(6);
    list2->next->next->next = createNode(8);
    list2->next->next->next -> next = createNode(18);

    printf("list1: ");
    printList(list1);

    printf("list2: ");
    printList(list2);

    // 合併 list1 和 list2
    struct node* merged = merge(list1, list2);

    printf("merged list: ");
    printList(merged);

    return 0;
}