有 nn 辆自行车依次来到停车棚,除了第一辆自行车外,每辆自行车都会恰好停放在已经在停车棚里的某辆自行车的左边或右边。(e.g.停车棚里已经有 33 辆自行车,从左到右编号为:3,5,13,5,1。现在编号为 22 的第 44 辆自行车要停在 55 号自行车的左边,所以现在停车棚里的自行车编号是:3,2,5,13,2,5,1)。给定nn辆自行车的停放情况,按顺序输出最后停车棚里的自行车编号。n\leq 100000n≤100000。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//自行车的总数
int num = sc.nextInt();//第一辆自行车的编号
doubleNode first = new doubleNode();//创建双向链表
first.data = num;
first.prior = null;
first.next = null;
doubleNode xx = null, yy = null;
doubleNode[] local = new doubleNode[100005];//存放自行车的地址
local[num] = first;//第一辆自行车的地址
for (int i = 1; i < n; i++) {//依次向双向链表中插入数据
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
xx = new doubleNode();
xx.data = x;
local[x] = xx;//编号为x的自行车地址
yy = new doubleNode();
yy = local[y];//获取编号y的自行车地址,存入的比x早
if(z == 0){//x放在y的左边
xx.next = yy;
if(yy.prior != null){//当yy结点不是头结点且将xx结点插入yy结点前面
xx.prior = yy.prior;
yy.prior.next = xx;
}else{
xx.prior = null;
}
yy.prior = xx;//y的前驱指针指向x
if(yy == first){//yy是头结点,则更改头结点
first = xx;
}
}
if(z == 1){//x放在y的右边
xx.prior = yy;
if(yy.next != null){//当yy结点不是尾结点且将xx结点插入yy结点的后面
xx.next = yy.next;
yy.next.prior = xx;
}else{
xx.next = null;
}
yy.next = xx;
}
}
while(first != null){
System.out.print(first.data+" ");
first = first.next;
}
}
}
class doubleNode{
int data;
doubleNode prior,next;
public doubleNode(){}
public doubleNode(int data,doubleNode prior,doubleNode next){
super();
this.data = data;
this.next = next;
this.prior = prior;
}
}