L2-022 重排链表 (25 分)
给定一个单链表 L1→L2→⋯→Ln−1→Ln,请编写程序将链表重新排列为 Ln→L1→Ln−1→L2→⋯。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。
输入格式:
每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N (≤105)。结点的地址是5位非负整数,NULL地址用−1表示。
接下来有N行,每行格式为:
Address Data Next
其中Address
是结点地址;Data
是该结点保存的数据,为不超过105的正整数;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
初看觉得难,细看发现是个水题。需要注意的是要注意多余结点。不然只能拿23分
上代码:
# include <iostream>
# include <numeric>
# include <algorithm>
# include <functional>
# include <list>
# include <map>
# include <set>
# include <stack>
# include <deque>
# include <queue>
# include <vector>
# include <ctime>
# include <cstdlib>
# include <cmath>
# include <string>
# include <cstring>
# include <iomanip>
# include <queue>
# include <cstdio>
using namespace std;
int const maxn = 1e5+ 5;
struct node
{
int address;
int data;
int next;
}s[maxn],temp[maxn];
int main(int argc, char *argv[])
{
int address, n;
cin >> address >> n;
for(int i = 0; i < n; i++)
{
int id;
cin >> id;
cin >> s[id].data;
cin >> s[id].next;
s[id].address = id;
}
for(int i = 0; i < n; i++)
{
temp[i] = s[address];
address = temp[i].next;
}
int index = n - 1;
for(int i = 0; i < n - 1; i++)
{
if(temp[i].next != temp[i + 1].address)
{
index = i;
break;
}
}
bool flag = false;
if(n & 1)
{
flag = true;
}
for(int i = 0, k = index; i <= k; i++, k--)
{
if(i == k && flag)
{
printf("%05d %d -1\n", temp[k].address, temp[k].data);
}
else
{
temp[k].next = temp[i].address;
temp[i].next = temp[k - 1].address;
printf("%05d %d %05d\n", temp[k].address, temp[k].data, temp[k].next);
if(i + 1 > k - 1)
{
// cout << i +1 << " " << k - 1 << endl;
printf("%05d %d -1\n", temp[i].address, temp[i].data);
}
else
{
printf("%05d %d %05d\n", temp[i].address, temp[i].data, temp[i].next);
}
}
}
return 0;
}