链表6(法二好理解)------ 7-6 sdut-C语言实验-有序链表的归并分数 20

简介: 链表6(法二好理解)------ 7-6 sdut-C语言实验-有序链表的归并分数 20

7-6 sdut-C语言实验-有序链表的归并


分数 20


全屏浏览


切换布局


作者 马新娟


单位 山东理工大学


分别输入两个有序的整数序列(分别包含M和N个数据),建立两个有序的单链表,将这两个有序单链表合并成为一个大的有序单链表,并依次输出合并后的单链表数据。


输入格式:

第一行输入M与N的值;

第二行依次输入M个有序的整数;

第三行依次输入N个有序的整数。


输出格式:

输出合并后的单链表所包含的M+N个有序的整数。


输入样例:

1. 6 5
2. 1 23 26 45 66 99
3. 14 21 28 50 100

输出样例:

1 14 21 23 26 28 45 50 66 99 100


代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

栈限制

8192 KB

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node*next;
};
int main()
{
    int m,n,i;
    scanf("%d %d",&m,&n);
    struct node *head1,*head2,*tail,*p,*q;
    head1=(struct node*)malloc(sizeof(struct node));
    head1->next=NULL;
    head2=(struct node*)malloc(sizeof(struct node));
    head2->next=NULL;
    tail=head1;
    for(i=0;i<m;i++)
    {
        p=(struct node*)malloc(sizeof(struct node));
        p->next=NULL;
        scanf("%d",&p->data);
        tail->next=p;
        tail=p;
 
    }
    tail=head2;
    for(i=0;i<n;i++)
    {
        p=(struct node*)malloc(sizeof(struct node));
        p->next=NULL;
        scanf("%d",&p->data);
        tail->next=p;
        tail=p;
    }
    struct node *p1,*p2;
    p1=head1->next;
    p2=head2->next;
    tail=head1;
    free(head2);
    while(p1&&p2)
    {
        if(p1->data<p2->data)
        {
            tail->next=p1;
            tail=p1;
            p1=p1->next;
        }
        else{
            tail->next=p2;
            tail=p2;
            p2=p2->next;
        }
    }
    if(p1)
    {
        tail->next=p1;
    }
    else{
        tail->next=p2;
    }
    p=head1->next;
    while(p)
    {
        if(p->next)
        {
            printf("%d ",p->data);
        }
        else{
            printf("%d\n",p->data);
        }
        p=p->next;
    }
 
 
    return 0;
}
目录
相关文章
|
4天前
链表9(优化版)7-9 sdut-C语言实验-约瑟夫问题
链表9(优化版)7-9 sdut-C语言实验-约瑟夫问题
7 0
|
4天前
链表5(考试用)7-5 sdut-C语言实验-链表的逆置
链表5(考试用)7-5 sdut-C语言实验-链表的逆置
7 0
|
4天前
链表8(法二考试专用)7-8 sdut-C语言实验-双向链表
链表8(法二考试专用)7-8 sdut-C语言实验-双向链表
4 0
|
4天前
链表4(法二)------7-4 sdut-C语言实验-单链表中重复元素的删除
链表4(法二)------7-4 sdut-C语言实验-单链表中重复元素的删除
5 0
|
4天前
|
机器学习/深度学习 存储
sdut pta 链表3(优化)-----7-3 sdut-C语言实验-链表的结点插入
sdut pta 链表3(优化)-----7-3 sdut-C语言实验-链表的结点插入
6 0
|
2月前
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解
|
28天前
|
存储 SQL 算法
LeetCode力扣第114题:多种算法实现 将二叉树展开为链表
LeetCode力扣第114题:多种算法实现 将二叉树展开为链表
|
28天前
|
存储 SQL 算法
LeetCode 题目 86:分隔链表
LeetCode 题目 86:分隔链表
|
1月前
|
存储 算法 Java
【经典算法】Leetcode 141. 环形链表(Java/C/Python3实现含注释说明,Easy)
【经典算法】Leetcode 141. 环形链表(Java/C/Python3实现含注释说明,Easy)
11 2
|
2月前
<数据结构>五道LeetCode链表题分析.环形链表,反转链表,合并链表,找中间节点.
<数据结构>五道LeetCode链表题分析.环形链表,反转链表,合并链表,找中间节点
29 1