版权声明:本文为博主原创文章,转载请注明出处( • ̀ω•́ )✧ https://blog.csdn.net/wangws_sb/article/details/88644986
给定一个单链表 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
解题思路:用m1 [i] 标记 i 结点的右相连结点,m2 [i] 标记 i 结点的左相连接点,s标记原链表的首节点,e标记原链表的尾结点,坑点是要考虑出现不止一个-1 的情况。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
const int N=1e5+7;
map <int,int> m1,m2;
int s,e,n;
int num[N];
int main()
{
int x,y,z;
cin>>s>>n;
int e=-1;
for(int i=0;i<n;i++){
cin>>x>>y>>z;
m1[x]=z;
m2[z]=x;
num[x]=y;
if(z==-1&&e==-1) e=x;
}
int i=0;
while(true){
if(i%2){
printf("%05d %d %05d\n",s,num[s],e);
s=m1[s];
}
else{
printf("%05d %d %05d\n",e,num[e],s);
e=m2[e];
}
if(s==e){
if(i%2) printf("%05d %d -1\n",s,num[s]);
else printf("%05d %d -1\n",e,num[e]);
break;
}
i++;
}
return 0;
}