3
I’m trying to create (I’m learning) a doubly chained list based on an exercise, in which the list will be a train with wagons. The exercise asks to create a class "wagon", where the variables "wagon name", "next wagon" and "previous wagon" are found, and to create another class "train", where the variables "head" and "Tail" are found, and the methods to add wagons, to print the wagons and another to change the order of the locomotives. My problem is how the exercise asks to create the method to add wagons. It passes as a parameter a variable that has not been declared, having as type of given the class "wagon", so I am not able to create this method. I’m going to show you what I did in the code below. Would anyone be able to give me a hint on this? Simply, I am not able to understand how I will use the parameter "vagueCriar" in the method.
In addition, the exercise calls for the creation of two trains, then two lists, and using the method to change the locomotives, to replace the locomotive of the first train with the locomotive of the second. Would you like to know, is it really possible to do this using a double-chained (or in this case, two) list? Because I’ve done enough research and I haven’t seen anything about it. I saw that it is possible to change the order of the elements of a list, but to change the elements between two lists, I am not sure.
public class Vagao {
String nomeDoVagao;
Wagon vagaoAnterior;
Wagon vagaoPosterior;
public Vagao (String nomeDoVagao){
this.nomeDoVagao = nomeDoVagao;
vagaoAnterior = null;
vagaoPosterior = null;
}
}
public class Trem {
Vagao head, tail = null;
//Não estou sabendo criar aqui
public void adicionarVagao (Vagao vagaoCriar){
Vagao novo_Vagao = new Vagao (vagaoCriar.nomeDoVagão);
if (head == null){
head = tail = novo_Vagao;
head.vagaoAnterior = null;
tail.vagaoPosterior = null;
} else {
tail.vagaoPosterior = novo_Vagao;
novo_Vagao.vagaoAnterior = tail;
tail = novo_Vagao;
tail.vagaoPosterior = null;
}
}
}