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

傷城~ 2023-02-22 10:59 87阅读 0赞

算法笔记总目录
Given two singly linked lists L​1​​=a​1​​→a​2​​→⋯→a​n−1​​→a​n​​ and L​2​​=b​1​​→b​2​​→⋯→b​m−1​​→b​m​​. If n≥2m, you are supposed to reverse and merge the shorter one into the longer one to obtain a list like a​1​​→a​2​​→b​m​​→a​3​​→a​4​​→b​m−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 L​1​​ and L​2​​, plus a positive N (≤10​5​​) 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:

Address Data Next
where Address is the position of the node, Data is a positive integer no more than 10​5​​, 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

题目未开放,代码只对样例进行了测试

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int maxn = 100005;
  4. struct Node{
  5. int address,data,nexto,nextt;
  6. }node[maxn];
  7. int main(){
  8. int s1,s2,n,k=0;
  9. cin>>s1>>s2>>n;
  10. for(int i=0;i<n;i++){
  11. int ad,data,next;
  12. cin>>ad>>data>>next;
  13. node[ad].data=data;
  14. node[ad].nexto=next;
  15. node[ad].address=ad;
  16. }
  17. while(node[s1].nexto != -1){ //反向链表建立
  18. int s=node[s1].nexto; //当前节点
  19. node[s].nextt=node[s1].address;
  20. s1=node[s1].nexto;
  21. }
  22. for(int i=1;i<n;i++){
  23. if(i%3==1){
  24. printf("%05d %d %05d\n",node[s2].address,node[s2].data,node[s2].nexto);
  25. s2=node[s2].nexto;
  26. }else if(i%3==2){
  27. printf("%05d %d %05d\n",node[s2].address,node[s2].data,node[s1].address);
  28. s2=node[s2].nexto;
  29. }else if(i%3==0){
  30. printf("%05d %d %05d\n",node[s1].address,node[s1].data,node[s2].address);
  31. s1=node[s1].nextt;
  32. }
  33. }
  34. if(n%3==0)printf("%05d %d -1\n",node[s1].address,node[s1].data);
  35. else printf("%05d %d -1\n",node[s2].address,node[s2].data);
  36. return 0;
  37. }

发表评论

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

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

相关阅读