重排链表 (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
题解思路都在代码块的注释里,经典的静态链表(小声比比:我不会),同级的一位大佬写的代码,通过地址first和end的互相迭代,来对数据进行输出。
下面是题解:
#include<iostream>
#include<algorithm>
#include<ctype.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<string>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<map>
#define ll long long
const int maxn = 1e5 + 10;
using namespace std;
struct node {
int before;//前驱
int data;
int next;//后驱
}a[maxn];
int main(){
int first,end,n;
cin>>first>>n;
for(int i=0;i<n;i++){
int address,data,next;
cin>>address>>data>>next;
a[address].data=data;
a[address].next=next;
if(next==-1){
end=address;//储存尾节点地址
}else {
a[next].before=address;//储存当前节点的前一个节点的地址
}
}
while (end!=a[first].before){//当头尾不相遇,进行循环
printf("%05d %d %05d\n",end,a[end].data,first);//输出后
end=a[end].before;
if(first==end){
printf("%05d %d -1\n",first,a[first].data);
break;
}
printf("%05d %d %05d\n",first,a[first].data,end);//输出前
first=a[first].next;
if(first==end){
printf("%05d %d -1\n",first,a[first].data);
break;
}
}
return 0;
}