您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之链表四:有序链表的归并

2018-03-24 16:57 363 查看

数据结构实验之链表四:有序链表的归并

Time Limit: 1000 ms
Memory Limit: 65536 KiB
[align=center]
[/align]

Problem Description

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

Input

第一行输入M与N的值;

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

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

Output

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

Sample Input

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


Sample Output

1 14 21 23 26 28 45 50 66 99 100


#include<stdio.h>

#include<stdlib.h>

struct node

{

    int data;

    struct node *next;

}*head1, *head2;

struct node *creat1(int m)

{

   int i;

   struct node *p, *tail1;

   head1 = (struct node*)malloc(sizeof(struct node));

   head1-> next = NULL;

   tail1 = head1;

   for(i = 1; i <= m; i++)

   {

       p = (struct node*)malloc(sizeof(struct node));

       p-> next = NULL;

       scanf("%d", &p-> data);

       tail1-> next = p;

       tail1 = p;

   }

   return head1;

}

struct node *creat2(int n)

{

   int i;

   struct node *q, *tail2;

   head2 = (struct node*)malloc(sizeof(struct node));

   head2-> next = NULL;

   tail2 = head2;

   for(i = 1; i <= n; i++)

   {

       q = (struct node*)malloc(sizeof(struct node));

       q-> next = NULL;

       scanf("%d", &q-> data);

       tail2-> next = q;

       tail2 = q;

   }

   return head2;

}

struct node *merge(struct node *head1, struct node *head2)

{

    struct node *q, *p, *tail;

    p = head1-> next;

    q = head2-> next;

    head1-> next = NULL;

    tail = head1;

    free(head2);

    while(p && q)

    {

        if(p-> data > q-> data)

        {

            tail-> next = q;

            tail = q;

            q = q-> next;

            tail-> next = NULL;

        }

        else

        {

            tail-> next = p;

            tail = p;

            p = p-> next;

            tail-> next = NULL;

        }

    }

    if(p)

    {

        tail-> next = p;

    }

    else

    {

        tail-> next = q;

    }

    return head1;

}

void print(struct node *head1)

{

    struct node *p;

    p = head1-> next;

    while(p != NULL)

    {

        if(p-> next != NULL)

        {

            printf("%d ", p-> data);

        }

        else

        {

            printf("%d\n", p-> data);

        }

        p = p-> next;

    }

}

int main(void)

{

    int m, n;

    struct node *h1, *h2, *h3;

    scanf("%d %d", &m, &n);

    h1 = creat1(m);

    h2 = creat2(n);

    h3 = merge(h1, h2);

    print(h3);

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: