zoukankan      html  css  js  c++  java
  • 数据结构实验之链表四:有序链表的归并

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

    Time Limit: 1000 ms Memory Limit: 65536 KiB

    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

    Hint

    不得使用数组!

    Source

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 struct node
     4 {
     5     int data;
     6     struct node *next;
     7 };
     8 struct node *Creat(int n)
     9 {
    10     struct node *head, *tail, *p;
    11     int i;
    12     head=(struct node *)malloc(sizeof(struct node));
    13     head->next=NULL;
    14     tail=head;
    15     for(i=1;i<=n;i++)
    16     {
    17         p=(struct node *)malloc(sizeof(struct node));
    18         scanf("%d",&p->data);
    19         p->next=NULL;
    20         tail->next=p;
    21         tail=p;
    22     }
    23     return head;
    24 }
    25 
    26 struct node * Merge(struct node *head1, struct node *head2)
    27 {
    28     struct node *p1, *p2, *tail;
    29     p1=head1->next;
    30     p2=head2->next;
    31     tail=head1;
    32     free(head2);
    33     while(p1&&p2)
    34     {
    35     if(p1->data < p2->data)
    36         {
    37             tail->next=p1;
    38             tail=p1;
    39             p1=p1->next;
    40         }
    41         else
    42         {
    43             tail->next=p2;
    44             tail=p2;
    45             p2=p2->next;
    46         }
    47     }
    48     if(p1)
    49         tail->next=p1;
    50     else
    51         tail->next=p2;
    52     return(head1);
    53 }
    54 
    55 int main()
    56 {
    57     struct node * head1, *head2, *p;
    58     int n, m;
    59     scanf("%d %d",&n,&m);
    60     head1=Creat(n);
    61     head2=Creat(m);
    62     p=Merge(head1,head2);
    63     while(p->next->next!=NULL)
    64     {
    65         printf("%d ",p->next->data);
    66         p=p->next;
    67     }
    68     printf("%d
    ",p->next->data);
    69     return 0;
    70 }
  • 相关阅读:
    regex正则表达式
    openfire+asmack
    vim 粘贴 取消缩进zz
    selenium自动化实战基于python语言(二: 编写脚本)
    Gparted硬盘管理工具
    selenium自动化实战基于python语言(一: 编写脚本)
    selenium自动化实战基于python语言(环境搭建)
    使Eclipse代码自动提示
    String相关的常见问题
    在Eclipse中查看JDK类库的源代码
  • 原文地址:https://www.cnblogs.com/xiaolitongxueyaoshangjin/p/12063670.html
Copyright © 2011-2022 走看看