1.题目
L2-022 重排链表
分数 25
全屏浏览
切换布局
作者 陈越
单位 浙江大学
给定一个单链表 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
2.分析
存储链表和元素顺序,然后更新元素的指向即可。
元素为奇数或偶数,链表的末尾元素下标不同。
3.代码
#include<iostream>
using namespace std;
const int MAX=100000;
//静态存储链表结构体
struct List{
int w,to=-1;
}list[MAX];
int root,N,arr[MAX],uns; //arr存储链表元素顺序
int main(){
cin>>root>>N;
int a,b,c;
for(int i=0;i<N;i++){
cin>>a>>b>>c;
list[a].w=b; //存储链表
list[a].to=c;
}
int t=root;
while(t!=-1){ //遍历链表存储元素顺序
arr[uns++]=t;
t=list[t].to;
}
for(int i=0;i<uns/2;i++){ //改变元素指向
list[arr[uns-1-i]].to=arr[i];
list[arr[i]].to=arr[uns-2-i];
}
if(uns%2==0){list[arr[uns/2-1]].to=-1;} //分情况讨论链表结尾
else{list[arr[uns/2]].to=-1;}
root=arr[uns-1];
while(root!=-1){ //遍历输出
if(list[root].to!=-1) printf("%05d %d %05d\n",root,list[root].w,list[root].to);
else printf("%05d %d %d\n",root,list[root].w,list[root].to);
root=list[root].to;
}
return 0;
}