2019 PAT甲级秋季考试7-2 Merging Linked Lists (25 分)

怼烎@ 2024-04-18 16:03 154阅读 0赞

Given two singly linked lists L1=a1→a2→⋯→an−1→an and L2=b1→b2→⋯→bm−1→bm. If n≥2m, you are supposed to reverse and merge the shorter one into the longer one to obtain a list like a1→a2→bm→a3→a4→bm−1⋯. For example, given one list being 6→7 and the other one 1→2→3→4→5, you must output 1→2→7→3→4→6→5.

Input Specification:

Each input file contains one test case. For each case, the first line contains the two addresses of the first nodes of L1 and L2, plus a positive N (≤105) which is the total number of nodes given. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

  1. Address Data Next

where Address is the position of the node, Data is a positive integer no more than 105, and Next is the position of the next node. It is guaranteed that no list is empty, and the longer list is at least twice as long as the shorter one.

Output Specification:

For each case, output in order the resulting linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

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

Sample Output:

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

题目很简单,保证长链一定比短链长2倍以上,直接开个新vector存就可以了

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<string>
  4. #include<math.h>
  5. #include<iostream>
  6. #include<vector>
  7. #include<algorithm>
  8. using namespace std;
  9. #define INF 0x3f3f3f3f
  10. struct node
  11. {
  12. int val,next;
  13. }p[100500];
  14. vector<int> v1,v2,v;
  15. void dfs1(int x)
  16. {
  17. if(x==-1)return;
  18. v1.push_back(x);
  19. dfs1(p[x].next);
  20. }
  21. void dfs2(int x)
  22. {
  23. if(x==-1)return;
  24. v2.push_back(x);
  25. dfs2(p[x].next);
  26. }
  27. int main()
  28. {
  29. int s1,s2,n,i,j,x,y,z;
  30. scanf("%d%d%d",&s1,&s2,&n);
  31. for(i=0;i<n;i++)
  32. {
  33. scanf("%d%d%d",&x,&y,&z);
  34. p[x].val=y;
  35. p[x].next=z;
  36. }
  37. dfs1(s1);
  38. dfs2(s2);
  39. //cout<<v1.size()<<" "<<v2.size()<<endl;
  40. if(v1.size()>v2.size())
  41. {
  42. int op=v2.size()-1;
  43. for(i=0;i<v1.size();i++)
  44. {
  45. v.push_back(v1[i]);
  46. if(i%2==1&&op>=0)
  47. v.push_back(v2[op--]);
  48. }
  49. }
  50. else
  51. {
  52. int op=v1.size()-1;
  53. for(i=0;i<v2.size();i++)
  54. {
  55. v.push_back(v2[i]);
  56. if(i%2==1&&op>=0)
  57. v.push_back(v1[op--]);
  58. }
  59. }
  60. for(i=0;i<v.size()-1;i++)
  61. printf("%05d %d %05d\n",v[i],p[v[i]].val,v[i+1]);
  62. printf("%05d %d -1\n",v[v.size()-1],p[v[v.size()-1]].val);
  63. }

发表评论

表情:
评论列表 (有 0 条评论,154人围观)

还没有评论,来说两句吧...

相关阅读