数据结构——链表之有序链表的归并

来源:互联网 发布:柯桥法院淘宝拍卖网 编辑:程序博客网 时间:2024/06/08 01:07

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

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

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

Input

第一行输入M与N的值; 
第二行依次输入M个有序的整数;
第三行依次输入N个有序的整数。

Output

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

Example Input

6 51 23 26 45 66 9914 21 28 50 100

Example Output

1 14 21 23 26 28 45 50 66 99 100

Hint

01#include <stdio.h>
02#include <stdlib.h>
03struct node
04{
05    int data;
06    struct node *next;
07};
08struct node *build(struct node *head,int n)
09{
10    int i;
11    struct node *p,*tail;
12    head->next=NULL;
13    tail=head;
14    for(i=1; i<=n; i++)
15    {
16        p=(struct node*)malloc(sizeof(struct node));
17        scanf("%d",&p->data);
18        p->next=tail->next;
19        tail->next=p;
20        tail=p;
21    }
22    return(head);
23}
24struct node *and(struct node *head1,struct node *head2)
25{
26    struct node *p,*q,*tail;
27    p=head1->next;
28    q=head2->next;
29    tail=head1;
30    while(p&&q)
31    {
32        if(p->data<=q->data)
33        {
34            tail->next=p;
35            tail=p;
36            p=p->next;
37        }
38        else
39        {
40            tail->next=q;
41            tail=q;
42            q=q->next;
43        }
44        if(p)
45            tail->next=p;
46        else
47            tail->next=q;
48    }
49    return(head1);
50};
51struct node *show(struct node *head)
52{
53    struct node *p;
54    p=(struct node*)malloc(sizeof(struct node));
55    p=head->next;
56    while(p)
57    {
58        printf("%d ",p->data);
59        p=p->next;
60    }
61    return(head);
62}
63int main()
64{
65    int m,n;
66    struct node *head1,*head2;
67    head1=(struct node*)malloc(sizeof(struct node));
68    head2=(struct node*)malloc(sizeof(struct node));
69    scanf("%d %d",&m,&n);
70    build(head1,m);
71    build(head2,n);
72    and(head1,head2);
73    show(head1);
74    return 0;
75}
76 
77 
78/***************************************************
79User name: jk160618郭衣鹏
80Result: Accepted
81Take time: 0ms
82Take Memory: 156KB
83Submit time: 2017-10-06 18:18:31
84****************************************************/
阅读全文
0 0
原创粉丝点击