L2-022 重排链表 【STL】

版权声明:本文为博主原创文章,转载请注明出处( • ̀ω•́ )✧ https://blog.csdn.net/wangws_sb/article/details/88644986

题目传送门

给定一个单链表 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

解题思路:用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;
}

猜你喜欢

转载自blog.csdn.net/wangws_sb/article/details/88644986