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 (≤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 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.
思路
采用静态链表的方法,把结点存到node数组里,再用循环把全部按链表的顺序存到vector里(重要!!!)。比较两个链表的大小,把小的链表放到v2里,再翻转v2。再把v1和v2里的数放到v3里,每3个数放一次v2的数。最后输出,要注意最后一位的next是-1,并且不足5位数的前面需要补0.
代码
#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
struct Node{
int data,next;
}node[100005];
vector<int> v1,v2,v3;
int main(){
int h1,h2,n,t;
scanf("%d%d%d",&h1,&h2,&n);
for(int i=0;i<n;i++){
scanf("%d",&t);
scanf("%d%d",&node[t].data,&node[t].next);
}
//按链表顺序存入vector
for(int p=h1;p!=-1;p=node[p].next)
v1.push_back(p);
for(int p=h2;p!=-1;p=node[p].next)
v2.push_back(p);
if(v1.size()<v2.size())//把更长的链表放到v1
swap(v1,v2);
reverse(v2.begin(),v2.end());
for(int i=0,j=0,k=0;i<v1.size()||j<v2.size();k++){
if((k+1)%3==0&&j<v2.size())
v3.push_back(v2[j++]);
else
v3.push_back(v1[i++]);
}
for(int i=0;i<v3.size();i++){
if(i==v3.size()-1) printf("%05d %d -1\n",v3[i],node[v3[i]]);
else printf("%05d %d %05d\n",v3[i],node[v3[i]],v3[i+1]);
}
}