重启c语言-两个有序链表序列的合并

PTA刷题第20题-两个有序链表序列的合并

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。

输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。

输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。

输入样例:

1 3 5 -1
2 4 6 8 10 -1

输出样例:

1 2 3 4 5 6 8 10

思路:将整个过程模块化,分为以下三个模块:一、链表的创建以及数据的读入。二、链表的合并。三、最终的链表的打印。
首先链表的创建函数如下:

struct node *creat()
{
    struct node *p1, *p2, *head1;
    p1=p2=head1=(struct node*)malloc(LEN);
    scanf("%d",&p1->x);
    head1 = NULL;
    int n = 0;
    while(p1->x != -1)
    {
        n++;
        if(n == 1)
            head1 = p1;
        else
            p2->next = p1;
        p2 = p1;
        p1 = (struct node *)malloc(LEN);
        scanf("%d",&p1->x);
    }
    p2->next = NULL;
    return head1;
}
 

可见,读入数据为-1时停止读入,并返回头指针。

之后需要对两个链表按照从小到大进行合并,合并的函数如下所示,其中
实参*p1以及 *p2分别为读入的两个链表的头指针。

struct node *findd(struct node *p1, struct node *p2)
{
    struct node *p3;
    p3 = NULL;
    if(p1 == NULL)
        return p2;
    if(p2 == NULL)
        return p1;
    if(p1->x < p2->x)
    {
        p3 = p1;
        p3->next = findd(p1->next,p2);
    }
    else
    {
        p3 = p2;
        p3->next = findd(p1,p2->next);
    }
    return p3;
}

最后打印出来最终的链表的数据:

void print(struct node *head)
{
    struct node *p;
    p = head;
    int n = 0;
    int flag = 0;
    while(p!=NULL)
    {
        flag = 1;
        n++;
        if(n == 1)
            printf("%d",p->x);
        else
            printf(" %d",p->x);
        p = p->next;
    }
    if(!flag)
        printf("NULL\n");
}

最终主函数如下:

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define LEN sizeof(struct node)
struct node
{
    int x;
    struct node *next;
};
int main()
{
    struct node *p, *head1, *head2;
    head1 = creat();
    head2 = creat();
    p = findd(head1, head2);
    print(p);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43723423/article/details/105202993