7-10 重排链表 (25分)

7-10 重排链表 (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 (≤10e​5​​ )。结点的地址是5位非负整数,NULL地址用−1表示。

接下来有N行,每行格式为:

Address Data Next

其中Address是结点地址;Data是该结点保存的数据,为不超过10e​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

AC

#include<bits/stdc++.h>
#include <iostream>
#include <algorithm>
using namespace std;

struct stu {
    
    
	int data;
	int next;
};
stu x[100001];
int main() {
    
    
	int h,n;
	cin>>h>>n;
	int a,b,c;
	for(int i=0; i<n; i++) {
    
    
		cin>>a>>b>>c;
		x[a].data=b;
		x[a].next=c;
	}
	int p[n+1],q=0;
	for(int i=h; i!=-1; i=x[i].next) {
    
    
		p[q++]=i;
	}
	int i=0,j=q-1;//这里原来的是j=n-1  改正之后就对了 不知道为什么 
	while(i<=j) {
    
    
		if(j==i||j-i==1) {
    
    
			if(j==i)
				printf("%05d %d -1\n",p[i],x[p[i]].data);
			else {
    
    
				printf("%05d %d %05d\n",p[j],x[p[j]].data,p[i]);
				printf("%05d %d -1\n",p[i],x[p[i]].data);
			}
		} else {
    
    
			printf("%05d %d %05d\n",p[j],x[p[j]].data,p[i]);
			printf("%05d %d %05d\n",p[i],x[p[i]].data,p[j-1]);
		}
		i++;
		j--;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45745322/article/details/112958370