Given two singly linked lists L1 =a1 →a2 →…→an-1 →an and L2 =b1 →b2 →…→bm-1 →bm. 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.
1.0.1. Input Specification
Each input file contains one test case. For each case, the first line contains the two addresses of the first nodes of L1and L2 , 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:
1
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.
#include<cstdio> #include<map> #include<vector> usingnamespace std; map<int,int> data,nextAdd; vector<int> v1,v2,ans; intmain(){ int f1,f2,n; scanf("%d%d%d",&f1,&f2,&n); for (int i = 0; i < n; ++i) { int a; scanf("%d",&a); scanf("%d%d",&data[a],&nextAdd[a]); } int len1 = 0; int len2 = 0; for (int i = f1; i != -1; i=nextAdd[i]) { len1++; v1.push_back(i); } for (int i = f2; i != -1; i=nextAdd[i]) { len2++; v2.push_back(i); }
if (len1>len2) { int i = 0; int j = len2-1; while(i<len1&&j>=0){ ans.push_back(v1[i++]); ans.push_back(v1[i++]); ans.push_back(v2[j--]); } while(i<len1){ ans.push_back(v1[i++]); } while(j>=0){ ans.push_back(v2[j--]); } }else{ int i = 0; int j = len1-1; while(i<len2&&j>=0){ ans.push_back(v2[i++]); ans.push_back(v2[i++]); ans.push_back(v1[j--]); } while(i<len2){ ans.push_back(v2[i++]); } while(j>=0){ ans.push_back(v1[j--]); } } for (int i = 0; i < ans.size(); ++i) { if (i!=ans.size()-1) { printf("%05d %d %05d\n",ans[i],data[ans[i]],ans[i+1]); }else{ printf("%05d %d -1\n", ans[i],data[ans[i]]); } } return0; }