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

typedef struct ListNode { int val; struct ListNode *next; } ListNode;

ListNode* createList() { ListNode *head, *tail, *node; int num;

head = (ListNode*)malloc(sizeof(ListNode));
head->next = NULL;
tail = head;

while (scanf("%d", &num) && num != -1) {
    node = (ListNode*)malloc(sizeof(ListNode));
    node->next = NULL;
    node->val = num;

    tail->next = node;
    tail = node;
}

return head;

}

ListNode* mergeLists(ListNode* head1, ListNode* head2) { if (head1 == NULL && head2 == NULL) { return NULL; } else if (head1 == NULL && head2 != NULL) { return head2; } else if (head1 != NULL && head2 == NULL) { return head1; }

ListNode *p1, *p2, *p3;
p1 = head1->next;
p2 = head2->next;
p3 = head1;
free(head2);

while (p1 && p2) {
    if (p1->val <= p2->val) {
        p3->next = p1;
        p3 = p1;
        p1 = p1->next;
    } else {
        p3->next = p2;
        p3 = p2;
        p2 = p2->next;
    }
}

if (p1) {
    p3->next = p1;
}
if (p2) {
    p3->next = p2;
}

return head1;

}

void showList(ListNode* head) { ListNode* curr = head->next; while (curr) { printf("%d", curr->val); if (curr->next) { printf(" "); } else { printf("\n"); } curr = curr->next; } }

int main() { ListNode *head1, *head2; head1 = createList(); head2 = createList();

head1 = mergeLists(head1, head2);

if (head1->next == NULL) {
    printf("NULL\n");
} else {
    showList(head1);
}

return 0;

}

C语言链表合并优化:代码简化、效率提升、变量重命名

原文地址: https://www.cveoy.top/t/topic/bGWV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录