Problem Description
分别输入两个有序的整数序列(分别包含M和N个数据),建立两个有序的单链表,将这两个有序单链表合并成为一个大的有序单链表,并依次输出合并后的单链表数据。
Input
第一行输入M与N的值;
第二行依次输入M个有序的整数;
第三行依次输入N个有序的整数。
第二行依次输入M个有序的整数;
第三行依次输入N个有序的整数。
Output
输出合并后的单链表所包含的M+N个有序的整数。
Example Input
6 5 1 23 26 45 66 99 14 21 28 50 100
Example Output
1 14 21 23 26 28 45 50 66 99 100
Hint
不得使用数组!
Author
01 | #include <iostream> |
02 | #include<stdio.h> |
03 | #include<stdlib.h> |
04 | using namespace std; |
05 | struct node |
06 | { |
07 | int date; |
08 | struct node* next; |
09 | }; |
10 | void Creatlist(node *&L, int n) |
11 | { |
12 | node *r,*s; |
13 | L= new node; |
14 | L->next=NULL; |
15 | r=L; |
16 | for ( int i=0;i<n;i++) |
17 | { |
18 | s= new node; |
19 | scanf ( "%d" ,&s->date); |
20 | s->next=NULL; |
21 | r->next=s; |
22 | r=s; |
23 | } |
24 | } |
25 | void MergeNode(node *&La,node *&Lb,node *&Lc) |
26 | { |
27 | node *pa,*pb,*pc; |
28 | pa=La->next; |
29 | pb=Lb->next; |
30 | Lc=pc=La; |
31 | while (pa&&pb) //当两个链表不同时为空时,进入循环 |
32 | { |
33 | if (pa->date<=pb->date) |
34 | { |
35 | pc->next=pa; |
36 | pc=pa; |
37 | pa=pa->next; |
38 | } |
39 | else |
40 | { |
41 | pc->next=pb; |
42 | pc=pb; |
43 | pb=pb->next; |
44 | } |
45 | } |
46 | pc->next=pa? pa:pb; //跳出循环时,两个链表中有一个为空,有一个还剩一个,让pc->next为不为空的呢个就可以 |
47 | } |
48 | void ShowNode(node *L) |
49 | { |
50 | node *p; |
51 | p=L->next; |
52 | while (p!=NULL) |
53 | { |
54 | printf ( "%d " ,p->date); |
55 | p=p->next; |
56 | } |
57 | } |
58 | int main() |
59 | { |
60 | int M,N,i; |
61 | node *La,*Lb,*Lc; |
62 | cin>>M>>N; |
63 | Creatlist(La,M); |
64 | Creatlist(Lb,N); |
65 | MergeNode(La,Lb,Lc); |
66 | ShowNode(Lc); |
67 |
68 | return 0; |
69 | } |
70 |
71 | /*************************************************** |
72 | User name: YT1558503112东野 |
73 | Result: Accepted |
74 | Take time: 0ms |
75 | Take Memory: 160KB |
76 | Submit time: 2016-12-13 13:20:00 |
77 | **************************************************** |