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

#include<iostream>

using namespace std;
const int MAXN=100005;
struct node{
	int data;//记录结点的值 
	int next;//记录其后继结点 
	int pre;//记录其前驱结点 
	node(){pre=-11;}
};
node h[MAXN];//输入链表的存储 
node th[MAXN];//重排链表的存储 
int main(){
	int head,n;//head 记录头节点的下标 
	int mo;//记录最后一个结点的下标 
	scanf("%d%d",&head,&n);
	for(int i=0;i<n;i++){
		int u,data,v;
		scanf("%d%d%d",&u,&data,&v);
		h[u].data=data;
		h[u].next=v;//记录后继结点 
		if(v!=-1) h[v].pre=u;//记录前驱结点 
		if(v==-1) mo=u;//记录尾结点 
	}
	//先把 n和1排一下 
	int t=mo;
	th[head].data=h[head].data;
	th[mo].data=h[mo].data;
	th[mo].next=head;
	th[head].next=-1;
	int temp=head;
	//mo 往前走  head往后走 
	mo=h[mo].pre;
	head=h[head].next;
	//重排剩余结点 
	while(n!=2){
		//如果head和mo相等则说明还剩一个结点 
		if(head==mo){ 
			th[temp].next=head;
			th[head].next=-1;
			th[head].data=h[head].data;
			break;
		}
		//head =h[mo].pre  说明还剩2个结点 
		if(head==h[mo].pre){
			th[temp].next=mo;
			th[mo].data=h[mo].data;
			th[mo].next=head;
			th[head].next=-1;
			th[head].data=h[head].data;
			break;
		}
		//链表重排 
		th[temp].next=mo;
		th[mo].data=h[mo].data;
		th[mo].next=head;
		th[head].next=-1;
		th[head].data=h[head].data;
		temp=head;
		mo=h[mo].pre;
		head=h[head].next;
	}
	while(t!=-1){
	if(th[t].next!=-1)
	printf("%05d %d %05d\n",t,th[t].data,th[t].next);
	else printf("%05d %d -1\n",t,th[t].data);
	t=th[t].next; 
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值