时间限制
500 ms
内存限制
64 MB
题目描述:
给定一个单链表 L 1 → L 2 → ⋯ → L n − 1 → L n L_{1} →L_{2} →⋯→L_{n−1} →L_{n} L1→L2→⋯→Ln−1→Ln ,请编写程序将链表重新排列为 L n → L 1 → L n − 1 → L 2 → ⋯ L_{n} →L_{1} →L_{n−1} →L_{2} →⋯ Ln→L1→Ln−1→L2→⋯。例如:给定L为 1 → 2 → 3 → 4 → 5 → 6 1→2→3→4→5→6 1→2→3→4→5→6,则输出应该为 6 → 1 → 5 → 2 → 4 → 3 6→1→5→2→4→3 6→1→5→2→4→3。
输入格式:
每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N (≤
1
0
5
10^{5}
105)。结点的地址是5位非负整数,NULL地址用−1表示。
接下来有N行,每行格式为:
Address Data Next
其中Address是结点地址;Data是该结点保存的数据,为不超过 1 0 5 10^{5} 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
给定一个链表
请按链表的 最后面一个和最前面一个的顺序 输出显示
emmmmmmm
先将链表的顺序安排出来
然后再从start头节点开始往后遍历链表 存储到list中
然后将list的一后一前拿出来输出
emmmmmmm
注: java 我最后一个样例过不去
import java.io.*;
import java.math.*;
import java.util.*;
public class Main
{
static int N = (int) 1e5;
static int shu[] = new int[N + 10]; // 当前节点存储的节点元素
static int ne[] = new int[N + 10]; // 当前节点指向的下一个节点
public static void main(String[] args) throws IOException
{
int start = sc.nextInt(); // 第一个节点
int n = sc.nextInt();
for (int i = 1; i <= n; i++)
{
int address = sc.nextInt(), data = sc.nextInt(), next = sc.nextInt();
shu[address] = data;
ne[address] = next;
}
ArrayList<Integer> L = new ArrayList<Integer>();
for (int i = start; i != -1; i = ne[i])
L.add(i);
ArrayList<Integer> res = new ArrayList<Integer>(); // 存储答案
int l = 0, r = L.size() - 1; // 存储两边分别到达哪里了
while (l < r)
{
res.add(L.get(r--));
res.add(L.get(l++));
}
if (l == r)
res.add(L.get(l));
int m = res.size() - 1;
for (int i = 0; i <= m; i++)
{
int x = res.get(i);
if (i == m)
out.printf("%05d %d %d\n", x, shu[x], -1);
else
out.printf("%05d %d %05d\n", x, shu[x], res.get(i + 1));
}
out.flush();
out.close();
}
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
}
c++
#include <iostream>
#include <vector>
using namespace std;
const int N = 1e5;
int shu[N + 10], ne[N + 10];
vector<int> L, res;
int main()
{
int start, n; scanf("%d%d", &start, &n);
for (int i = 1; i <= n; i++)
{
int address, data, next; scanf("%d%d%d", &address, &data, &next);
shu[address] = data;
ne[address] = next;
}
for (int i = start; i != -1; i = ne[i])
L.push_back(i);
int l = 0, r = L.size() - 1; // 存储两边分别到达哪里了
while (l < r)
{
res.push_back(L[r --]);
res.push_back(L[l ++]);
}
if (l == r)
res.push_back(L[l]);
int m = res.size() - 1;
for (int i = 0; i <= m; i++)
{
int x = res[i];
if (i == m)
printf("%05d %d %d\n", x, shu[x], -1);
else
printf("%05d %d %05d\n", x, shu[x], res[i + 1]);
}
return 0;
}
如果有说错的 或者 不懂的 尽管提 嘻嘻
一起进步!!!