题目详情 - L2-022 重排链表 (25 分) (pintia.cn)
思路:先通过数组生成链表,然后通过vector控制前后关系即可。
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
const int N = 100010;
int e[N],ne[N];
int main(){
int n,h;
cin>>h>>n;
memset(ne,-1,sizeof ne);
for(int i = 0; i < n; i++){
int a,b,c;
cin>>a>>b>>c;
e[a] = b;
ne[a] = c;
}
vector<int> ls;
int t = h;
while(t != -1){
ls.push_back(t);
t = ne[t];
}
vector<int> res;
int sz = ls.size();
for(int i = 0; i < sz/2; i++){
res.push_back(ls[sz-1-i]);
res.push_back(ls[i]);
}
if(res.size() < sz) res.push_back(ls[sz/2]);
for(int i = 0; i < res.size(); i++){
printf("%05d %d ",res[i],e[res[i]]);
if(i != res.size()-1) printf("%05d\n",res[i+1]);
else puts("-1");
}
return 0;
}
|