自行车停放
问题描述
有n辆自行车依次来到停车棚,除了第一辆自行车外,每辆自行车都会恰好停放在已经在停车棚里的某辆自行车的左边或右边。(e.g.停车棚里已经有3辆自行车,从左到右编号为:3,5,1。现在编号为2的第4辆自行车要停在5号自行车的左边,所以现在停车棚里的自行车编号是:3,2,5,1)。给定n辆自行车的停放情况,按顺序输出最后停车棚里的自行车编号。
输入格式
第一行一个整数n。
第二行一个整数x。表示第一辆自行车的编号。
以下n-1行,每行3个整数x,y,z。
z=0时,表示编号为x的自行车恰停放在编号为y的自行车的左边
z=1时,表示编号为x的自行车恰停放在编号为y的自行车的右边
输出格式
从左到右输出停车棚里的自行车编号
样例输入
4
3
1 3 1
2 1 0
5 2 1
样例输出
3 2 5 1
解题思路:自己实现一个双向链表,如果直接使用LinkedList,每次插入都需要寻找y的位置,大数据时超时
package text;
import java.util.Scanner;
public class Main {
static class bike {
int num = -1;
bike left = null;
bike right = null;
bike(int num) {
this.num = num;
left = null;
right = null;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int st = sc.nextInt();
bike first = new bike(st);
bike[] ind = new bike[1000000];//地址寄存方便寻找
ind[st] = first;
for (int i = 0; i < n - 1; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
bike now = new bike(x);
ind[x] = now;//存储x号自行车的地址
bike p = ind[y];//寻找y号自行车的地址
if (z == 0) {
now.right = p;
now.left = p.left;
if (p.left != null) {
p.left.right = now;
}
p.left = now;
if (p == first) {//插入到原表头之前
first = now;//更换表头
}
} else if (z == 1) {
now.left = p;
now.right = p.right;
if (p.right != null) {
p.right.left = now;
}
p.right = now;
}
}
while (first != null) {
System.out.print(first.num + " ");
first = first.right;
}
}
}