PTAL2-022 重排链表(链表)
Description
给定一个单链表 L1→L2→⋯→Ln−1→Ln,请编写程序将链表重新排列为 n→L1→Ln−1→L2→⋯。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。
Input
每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N(≤10
5)。结点的地址是5位非负整数,NULL地址用−1表示。
接下来有N行,每行格式为:Address Data Next其中Address是结点地址;Data是该结点保存的数据,为不超过105的正整数;Next是下一结点的地址。题目保证给出的链表上至少有两个结点。
Output
对每个测试用例,顺序输出重排后的结果链表,其上每个结点占一行,格式与输入相同。
Sample Input
00100 6
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
Sample Output
68237 6 00100
00100 1 99999
99999 5 12309
12309 2 00000
00000 4 33218
33218 3 -1
题意
输入一个链表,按照题目的要求重新排序
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<stack>
#include<vector>
#include<functional>
#include<map>
using namespace std;
typedef long long ll;
const int N=1e5+10,NN=2e3+10,INF=0x3f3f3f3f;
const ll MOD=1e9+7;
struct Node{
int head;//地址
int value;//值
int next;//下一个结点的地址
int tag;//重新排序后的下标
bool friend operator<(const Node &a,const Node &b){//根据下标从小到大排序
return a.tag<b.tag;
}
}node[N];
int head,n;
void init(){
for(int i=0;i<N;i++) node[i].tag=INF;//将tag赋值为INF,表示将没有存值过的结构体放在后面
}
int main(){
init();
scanf("%d%d",&head,&n);
for(int i=1;i<=n;i++){
int u,w,v;
scanf("%d%d%d",&u,&w,&v);
node[u].head=u;
node[u].value=w;
node[u].next=v;
}
int sum=0;
while(head!=-1){
node[head].tag=sum++;//给下表赋值
head=node[head].next;
}
sort(node,node+N);//重排链表
for(int i=0;i<sum/2;i++){
printf("%05d %d %05d\n",node[sum-i-1].head,node[sum-i-1].value,node[i].head);
printf("%05d %d ",node[i].head,node[i].value);
if(i!=sum/2-1) printf("%05d\n",node[sum-i-2].head);
}
if(sum%2==1) printf("%05d\n%05d %d ",node[sum/2].head,node[sum/2].head,node[sum/2].value);//因为当给出的元素是奇数个的时候,会少输出最后一个结点
printf("-1\n");
}