2-3 链表拼接 (20分)-HBU DS

    科技2024-11-30  7

    2-3 链表拼接 (20分)

    本题要求实现一个合并两个有序链表的简单函数。链表结点定义如下:

    struct ListNode { int data; struct ListNode *next; };

    函数接口定义:

    struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2);

    其中list1和list2是用户传入的两个按data升序链接的链表的头指针;函数mergelists将两个链表合并成一个按data升序链接的链表,并返回结果链表的头指针。

    裁判测试程序样例:

    #include <stdio.h> #include <stdlib.h> struct ListNode { int data; struct ListNode *next; }; struct ListNode *createlist(); /*裁判实现,细节不表*/ struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2); void printlist( struct ListNode *head ) { struct ListNode *p = head; while (p) { printf("%d ", p->data); p = p->next; } printf("\n"); } int main() { struct ListNode *list1, *list2; list1 = createlist(); list2 = createlist(); list1 = mergelists(list1, list2); printlist(list1); return 0; } /* 你的代码将被嵌在这里 */

    输入样例:

    1 3 5 7 -1 2 4 6 -1

    输出样例:

    1 2 3 4 5 6 7

    代码

    struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2) { struct ListNode *L = (struct ListNode *)malloc(sizeof(struct ListNode)), *temp; L->next = NULL; temp = L; struct ListNode *pa, *pb; pa = list1, pb = list2; while (pa && pb) { if (pa->data == pb->data) { temp->next = pa; temp = temp->next; pa = pa->next; } else if (pa->data > pb->data) { temp->next = pb; temp = temp->next; pb = pb->next; } else { temp->next = pa; temp = temp->next; pa = pa->next; } } if (pa) temp->next = pa; if (pb) temp->next = pb; return L->next; }
    Processed: 0.047, SQL: 8