给定一个单链表 L
1
→L
2
→⋯→L
n−1
→L
n
,请编写程序将链表重新排列为 L
n
→L
1
→L
n−1
→L
2
→⋯。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。
输入格式:
每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N (≤10
5
)。结点的地址是5位非负整数,NULL地址用−1表示。
接下来有N行,每行格式为:
Address Data Next
其中Address是结点地址;Data是该结点保存的数据,为不超过10
5
的正整数;Next是下一结点的地址。题目保证给出的链表上至少有两个结点。
输出格式:
对每个测试用例,顺序输出重排后的结果链表,其上每个结点占一行,格式与输入相同。
输入样例:
00100 6
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
输出样例:
68237 6 00100
00100 1 99999
99999 5 12309
12309 2 00000
00000 4 33218
33218 3 -1
遍历的时候,用n就有一个点不过,用size就过,不知道为什么
#include <bits/stdc++.h>
#define pb push_back
#define mem(a,b) memset(a,b,szieof a)
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
struct Node
{
int add;
int data;
int next;
}link[100010];//下标为地址
int main()
{
// freopen("D:\\LYJ.txt","r",stdin);
vector<int> o;//存顺序情况的地址
int sa,n,t,l;
cin>>sa>>n;
l=n;
while(l--)
{
cin>>t;
cin>>link[t].data;
cin>>link[t].next;
link[t].add=t;
}
while(sa!=-1)
{
o.pb(sa);
sa=link[sa].next;
}
n=o.size();//用n就有一个点不过,用size就过
for(int i=0;i<n/2;i++)
{
if(!i) printf("%05d %d ",o[n-i-1],link[o[n-i-1]].data);
else printf("%05d\n%05d %d ",o[n-i-1],o[n-i-1],link[o[n-i-1]].data);
printf("%05d\n%05d %d ",o[i],o[i],link[o[i]].data);
}
if(n%2!=0) printf("%05d\n%05d %d ",o[n/2],o[n/2],link[o[n/2]].data);
cout<<"-1";
return 0;
}