给定一个单链表 L1→L2→⋯→Ln−1→Ln,请编写程序将链表重新排列为 Ln→L1→Ln−1→L2→⋯。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。
接下来有N行,每行格式为:
Address Data 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
测试点2 就是链表是奇数的情况;
测试点3 则是链表会小于n
我这种只需要注意奇数偶数就可以
#include<bits/stdc++.h>
using namespace std;
struct M
{
int chu;
int zhi;
int next1;
};
M p[100010];
int p1[100010];//记录顺序
int main()
{
int n, n1;
cin >> n >> n1;
while (n1--)
{
int a, b, c;
cin >> a >> b >> c;
p[a].chu = a;
p[a].next1 = c;
p[a].zhi = b;
}
int q = 0;
while (n != -1)
{
p1[q++] = p[n].chu;
n = p[n].next1;
}
int l = q - 1;
int l1 = 0;
while (l1 < l)
{
printf("%05d %d %05d\n", p[p1[l]].chu, p[p1[l]].zhi, p[p1[l1]].chu);
printf("%05d %d ", p[p1[l1]].chu, p[p1[l1]].zhi);
if (l > l1 + 1) printf("%05d\n", p[p1[l - 1]].chu);
else cout << -1 << endl;
l--;
l1++;
}
if (q % 2 != 0) printf("%05d %d -1", p[p1[l]].chu, p[p1[l]].zhi);
return 0;
}
因篇幅问题不能全部显示,请点此查看更多更全内容