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.
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.
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.
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
属于甲级常考的静态链表题目。如果想了解静态链表题的思路可以先去看晴神宝典。
第一种写法就是晴神宝典的写法,用排序,只用一个vector,并且会修改到新链表的next项。
第二种写法就是参考1133柳神的写法,不同排序,用多个vector,不用修改next项。
第三种写法是第二种写法的优化(大家直接看她的就可以了):https://blog.csdn.net/Exupery_/article/details/100698828
#include
#include
#include
#include
#include
#include
#include
using namespace std;
struct node{
int id,data,next;
};
node a[100005];
int main(){
int ba,bb,n,s,d,e;
scanf("%d %d %d\n",&ba,&bb,&n);
vector va,vb,ans;
for(int i=0;ivb.size()){
int j=(int)vb.size()-1;
for(int i=0;i0 && i%2==0 && j>=0){
ans.push_back(vb[j]);
j--;
}
ans.push_back(va[i]);
if(i==va.size()-1 && j==0){
ans.push_back(vb[j]);
}
}
}else {
int j=(int)va.size()-1;
for(int i=0;i0 && i%2==0 && j>=0){
ans.push_back(va[j]);
j--;
}
ans.push_back(vb[i]);
if(i==vb.size()-1 && j==0){
ans.push_back(va[j]);
}
}
}
for(int i=0;i
//输入1
00100 01000 6
02233 2 34891
00100 6 00001
34891 3 10086
01000 1 02233
10086 4 -1
00001 7 -1
//输出1
01000 1 02233
02233 2 00001
00001 7 34891
34891 3 10086
10086 4 00100
00100 6 -1
//输入2
00100 01000 8
02233 2 34891
00100 7 00001
34891 3 10086
01000 1 02233
00033 5 02342
10086 4 00033
00001 8 -1
02342 6 -1
//输出2
01000 1 02233
02233 2 00001
00001 8 34891
34891 3 10086
10086 4 00100
00100 7 00033
00033 5 02342
02342 6 -1
//输入3
01000 00033 3
02233 2 -1
01000 1 02233
00033 3 -1
//输出3
01000 1 02233
02233 2 00033
00033 3 -1
//输入4
00033 01000 3
02233 2 -1
01000 1 02233
00033 3 -1
//输出4
01000 1 02233
02233 2 00033
00033 3 -1
//输入6:游离节点不能输出
02233 01000 6
02233 2 00033
01000 1 -1
00033 3 23421
23421 4 -1
27834 9 78932
78932 8 -1
//输出6
02233 2 00033
00033 3 01000
01000 1 23421
23421 4 -1