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
题解:
读入->排序->模拟
需要注意的是数据比较坑(第4个点),可能存在不再一个链表上的两个结点,所有需要记录一下链表长度。
#include <iostream>
#include <map>
using namespace std;
struct node
{
string address;
int data;
string next;
}a[100010],s,tmp;
map<string,node> mp;
int main()
{
cin>>s.address>>s.data;
for(int i=0;i<s.data;i++)
{
cin>>tmp.address>>tmp.data>>tmp.next;
mp[tmp.address]=tmp;
}
int len=0;
for(int i=0;i<s.data;i++)
{
len++;
a[i]=mp[s.address];
s.address=a[i].next;
if(s.address=="-1")break;
}
int count=1;
for(int i=0;i<(len+1)/2;i++)
{
if(count%2==1)
{
cout<<a[len-i-1].address<<" "<<a[len-i-1].data<<" ";
if(count!=len)
{
cout<<a[i].address<<endl;
}
else
{
cout<<-1<<endl;
break;
}
count++;
}
if(count%2==0)
{
cout<<a[i].address<<" "<<a[i].data<<" ";
if(count!=len)
{
cout<<a[len-i-2].address<<endl;
}
else
{
cout<<-1<<endl;
break;
}
count++;
}
}
return 0;
}