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

题目描述:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
(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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值