[剑指offer-1519]合并两个排序的链表

来源:互联网 发布:电脑怎么隐藏软件 编辑:程序博客网 时间:2024/05/29 06:50

题目描述:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
(hint: 请务必使用链表。)
输入:
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为两个整数n和m(0<=n<=1000, 0<=m<=1000):n代表将要输入的第一个链表的元素的个数,m代表将要输入的第二个链表的元素的个数。
下面一行包括n个数t(1<=t<=1000000):代表链表一中的元素。接下来一行包含m个元素,s(1<=t<=1000000)。
输出:
对应每个测试案例,
若有结果,输出相应的链表。否则,输出NULL。
样例输入:
5 2
1 3 5 7 9
2 4
0 0
样例输出:
1 2 3 4 5 7 9
NULL

#include <stdio.h>#include <stdlib.h>typedef struct Node{    int value;    struct Node* next;}Node,*pNode;pNode createList(int n){    pNode head = NULL;    pNode current = NULL;    while(n--){        int value;        scanf("%d",&value);        pNode newNode = (pNode)malloc(sizeof(Node));        newNode->value =value;        newNode->next = NULL;        if(head == NULL){            head = newNode;            current = head;        }else{            current->next = newNode;            current = current->next;        }    }    return head;}pNode mergeList(pNode list1 , pNode list2){    if(list1 == NULL)        return list2;    if (list2 == NULL) {        return list1;    }    pNode mergeHead = NULL;    if(list1->value < list2->value){        mergeHead = list1;        mergeHead->next = mergeList(list1->next, list2);    }else{        mergeHead = list2;        mergeHead->next = mergeList(list2->next,list1);    }    return mergeHead;}void printList(pNode head){    if(head == NULL){        printf("NULL\n");        return;    }    pNode tmp = head;    while (tmp) {        if(tmp->next == NULL)            printf("%d\n",tmp->value);        else            printf("%d ",tmp->value);        tmp = tmp->next;    }}int main(int argc, const char * argv[]) {    // insert code here...    int m , n;    while (scanf("%d %d",&n,&m)!=EOF) {        pNode list1 = createList(n);        pNode list2 = createList(m);        pNode merge = mergeList(list1, list2);        printList(merge);    }    return 0;}
0 0
原创粉丝点击