L2-022. 重排链表

来源:互联网 发布:淘宝客优惠券加人 编辑:程序博客网 时间:2024/05/14 00:03

给定一个单链表 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 600000 4 9999900100 1 1230968237 6 -133218 3 0000099999 5 6823712309 2 33218
输出样例:
68237 6 0010000100 1 9999999999 5 1230912309 2 0000000000 4 3321833218 3 -1
一道模拟,开始想复杂了。。。
#include<iostream>#include<cstdio>using namespace std;struct node{int data;int next;}x[100001];int main(){int s,n;scanf("%d%d",&s,&n);for(int i=0;i<n;i++){int add;int d;int nx;scanf("%d%d%d",&add,&d,&nx);x[add].data=d;x[add].next=nx;}int cnt=0;int res[100005];int res2[100005];while(s!=-1){res[cnt++]=s;s=x[s].next;}int l=0;int r=cnt-1;int cnt2=0;while(l<=r){if(l==r)res2[cnt2++]=res[r--];else{res2[cnt2++]=res[r--];res2[cnt2++]=res[l++];}}for(int i=0;i<cnt-1;i++){printf("%05d %d %05d\n",res2[i],x[res2[i]].data,res2[i+1]);}printf("%05d %d -1\n",res2[cnt-1],x[res2[cnt-1]].data);return 0;}


原创粉丝点击