PAT(乙级)2019年秋季考试 7-5 链表合并 (25分)

7-5 链表合并 (25分)
 

给定两个单链表 L1​​=a1​​a2​​an1​​an​​ 和 L2​​=b1​​b2​​bm1​​bm​​。如果 n2m,你的任务是将比较短的那个链表逆序,然后将之并入比较长的那个链表,得到一个形如 a1​​a2​​bm​​a3​​a4​​bm1​​⋯ 的结果。例如给定两个链表分别为 6→7 和 1→2→3→4→5,你应该输出 1→2→7→3→4→6→5。

输入格式:

输入首先在第一行中给出两个链表 L1​​ 和 L2​​ 的头结点的地址,以及正整数 N (≤),即给定的结点总数。一个结点的地址是一个 5 位数的非负整数,空地址 NULL 用 -1 表示。

随后 N 行,每行按以下格式给出一个结点的信息:

Address Data Next
 

其中 Address 是结点的地址,Data 是不超过 1 的正整数,Next 是下一个结点的地址。题目保证没有空链表,并且较长的链表至少是较短链表的两倍长。

输出格式:

按顺序输出结果链表,每个结点占一行,格式与输入相同。

输入样例:

00100 01000 7
02233 2 34891
00100 6 00001
34891 3 10086
01000 1 02233
00033 5 -1
10086 4 00033
00001 7 -1
 

输出样例:

01000 1 02233
02233 2 00001
00001 7 34891
34891 3 10086
10086 4 00100
00100 6 00033
00033 5 -1


代码讲解:依据题意你首先要找出,哪个长,我是把各个链表,又
组合成了数组,方便把短的逆转,之后方便慢慢插。


 1 #include<stdio.h>
 2 typedef struct 
 3 {
 4     int address;
 5     int data;
 6     int next;
 7 }lnode;
 8 lnode s[100000],a[100000],b[100000],c[100000];
 9 int count_lnode(int start,lnode a[])
10 {
11     int count=0;
12     while(start!=-1)
13     {
14         a[count++]=s[start];
15         start=s[start].next;
16     }
17     return count;
18     
19 }
20 void result(int count_big,lnode *a,int count_small,lnode *b,lnode result[])
21 {
22     int i,j,k;
23     for(i=0,j=0,k=0;i<count_big+count_small;i++)
24     {
25         if(i%3==2&&k<count_small)
26         result[i]=b[k++];
27         else
28         result[i]=a[j++];
29     }
30 }
31 void reverse(lnode a[],int count)
32 {
33     int i;
34     lnode temp;
35     for(i=0;i<count/2;i++)
36     {
37         temp=a[i];
38         a[i]=a[count-i-1];
39         a[count-i-1]=temp;
40     }
41 }
42 int main()
43 {
44     int start1,start2,count_a,count_b,n,i,address,data,next;
45     scanf("%d %d %d",&start1,&start2,&n);
46     for(i=0;i<n;i++)
47     {
48         scanf("%d %d %d",&address,&data,&next);
49         s[address].address=address;
50         s[address].data=data;
51         s[address].next=next;
52     }
53     count_a=count_lnode(start1,a);
54     count_b=count_lnode(start2,b);
55     if(count_a>count_b)
56     {
57         reverse(b,count_b);
58         result(count_a,a,count_b,b,c);
59     }
60     else
61     {
62         reverse(a,count_a);
63         result(count_b,b,count_a,a,c);
64     }
65     for(i=0;i<count_a+count_b-1;i++)
66     {
67            printf("%05d %d %05d\n",c[i].address,c[i].data,c[i+1].address);
68     }
69     printf("%05d %d -1\n",c[i].address,c[i].data);
70     return 0;
71 }

 

 
posted @ 2020-12-02 22:08  罪梦者  阅读(193)  评论(0)    收藏  举报