У меня есть домашнее задание: мне нужно создать двойной круговой связанный список для пользовательского интерфейса музыкального проигрывателя. Я написал метод addFirst, и он работает нормально, но когда я создаю метод addLast, я, похоже, не могу отличить хвост от головы. На самом деле я добавляю одно и то же место в обоих методах, но каким-то образом он должен знать, что одно — это новая голова, а другое — новый хвост. Я просмотрел Интернет и обнаружил, что на каждой странице они делают одно и то же, поэтому я застрял.
class DoublyCircularLinkedList implements IDoublyCircularLinkedList {
//instance variables
private Node current; // The current node in the list
private Node head; // The head node in the list
private int size = 0; // The size of the list
//constructor
public DoublyCircularLinkedList() {
current = null;
head = null;
size = 0;
}
// Adds an element to the head of the list
@Override
public void addFirst(T data) {
if (data instanceof Music) {
Music musicData = (Music) data;
File songFile = new File(musicData.getPath());
if (!songFile.exists()) {
System.out.println("Song file does not exist: " + musicData.getPath());
return; // Stop if the song file doesn't exist
}
}
Node newNode = new Node(data);
if (size == 0) {
current = newNode;
head = newNode;
newNode.setNext(newNode);
newNode.setPrev(newNode);
size++;
}
else {
Node tail = head.getPrev();
newNode.setNext(head);//setting new nodes next node to head
head.setPrev(newNode);
newNode.setPrev(tail);
tail.setNext(newNode);
head = newNode;//setting the new node as the head
current = newNode;
size++;
}
}
// Adds an element to the tail of the list
@Override
public void addLast(T data) {
if (data instanceof Music) {
Music musicData = (Music) data;
File songFile = new File(musicData.getPath());
if (!songFile.exists()) {
System.out.println("Song file does not exist: " + musicData.getPath());
return; // Stop if the song file doesn't exist
}
}
Node newNode = new Node(data);
if (size == 0) {
current = newNode;
head = newNode;
newNode.setNext(newNode);
newNode.setPrev(newNode);
size++;
}
else {
Node tail = head.getPrev();
newNode.setPrev(tail);
tail.setNext(newNode);
newNode.setNext(head);
head.setPrev(newNode);
current = newNode;
size++;
}
}}
Подробнее здесь: https://stackoverflow.com/questions/790 ... the-tail-i