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

来源:互联网 发布:炉石百宝箱 mac 编辑:程序博客网 时间:2024/05/21 17:08

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

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

不得使用数组!

Author

 
   01#include<bits/stdc++.h>
02using namespace std;
03typedef struct node
04{
05    int data;
06    struct node *next;
07}_list;
08
09_list *creat(int n)
10{
11    _list *head, *p ,*tail;
12    head=new node;
13    head->next=NULL;
14    tail=head;
15    while(n--)
16    {
17        p=new node;
18        cin>>p->data;
19        p->next =NULL;
20        tail->next =p;
21        tail=p;
22    }
23    return  head;
24}
25
26_list *link(_list *head1, _list *head2)
27{
28    _list *p=head1->next, *q= head2->next ,*tail;
29    head1->next= NULL;
30    tail=head1;
31    while(p&&q)
32    {
33        if(p->data > q->data)
34        {
35           tail->next = q;
36            tail=q;
37            q = q->next ;
38        }
39        else
40        {
41            tail->next = p;
42            tail=p;
43            p=p->next;
44        }
45    }
46    if(p)
47        tail->next =p;
48    else tail->next =q;
49    return head1;
50}
51
52void print(_list *head)
53{
54    _list *p=head->next;//这里之前错了、和_list *p;head->next=p;有何区别?
55    while(p->next)
56    {
57        cout <<p->data<<" ";
58        p=p->next ;
59    }
60    cout <<p->data<<endl;
61}
62
63int main()
64{
65    int m,n;
66    _list *head1,*head2;
67    cin>>m>>n;
68    head1 = creat(m);
69    head2 = creat(n);
70    head1 = link(head1,head2);
71    print(head1);
72    return 0;
73}
//以后在做题时,建议更多的用函数,因为在以后的工作岗位上,免不了的
0 0
原创粉丝点击