7-9 重排链表 (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 (≤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
这种给地址的连标题我现在是在结构体先构造好struct,然后按下标输入给的东西
用一个vector记下来从头地址一直到尾地址的所有地址,之后再进行题目的操作,比如重排,分类,翻转等
这题唯一注意的点就在输出上了,如果像我这样元素除2然后尾头依次遍历要注意奇数情况,要单独把除二那个元素输出
#include<iostream>
#include<vector>
#include<cstdio>
using namespace std;
struct LNode
{
int add;
int data;
int next;
}List[100000];
int main()
{
int fa, n;
vector<int>ls;
cin >> fa >> n;
for (int i = 0; i < n; i++)
{
int temp;
cin >> temp;
cin >> List[temp].data;
cin >> List[temp].next;
List[temp].add = temp;
}
while (fa != -1)
{
ls.push_back(fa);
fa = List[fa].next;
}
for (int i = 0; i < ls.size()/2; i++)
{
if (!i)
printf("%05d %d ", ls[ls.size() - 1 - i], List[ls[ls.size() - 1 - i]].data);
else
printf("%05d\n%05d %d ", ls[ls.size() - 1 - i], ls[ls.size() - 1 - i], List[ls[ls.size() - 1 - i]].data);
printf("%05d\n%05d %d ", ls[i], ls[i], List[ls[i]].data);
}
if (ls.size() % 2 != 0)
{
printf("%05d\n%05d %d ", ls[ls.size() / 2], ls[ls.size() / 2], List[ls[ls.size() / 2]].data);
}
cout << -1;
return 0;
}
其他链表操作题:
1075 链表元素分类 (25 分):
https://blog.csdn.net/ScreaM__/article/details/84894954
1025 反转链表 (25 分):
https://blog.csdn.net/ScreaM__/article/details/84895022