I\'m stuck on these methods i\'m trying to implement. I have to use a queue with
ID: 3863215 • Letter: I
Question
I'm stuck on these methods i'm trying to implement. I have to use a queue with a doubly linked list. Basically I need to be able to add new elements to the queue but I also need to iterate through and compare all the items in the queue and if they are equal, I need to set it as a child to that "parent" node. I am not sure how to do this, I've tried multiple different ways. I also need to keep track of the size and totalSize (including child nodes). My setChild method just accepts a parameter and sets the field child to the parameter. Any help would be really appreciated, thank you. Also this is supposed to be in Java.
@Override
public void enqueue(T element) throws NonComparableElementException {
TernaryNode<T> temp = new TernaryNode<>(element);
if (head == null) {
head = temp;
tail = temp;
size = 1;
totalSize = 1;
return;
}
int scan = 0;
TernaryNode<T> current = head;
TernaryNode<T> previous = null;
Friend cur = (Friend) current.getElement();
while (scan < totalSize && cur.compareTo(element) == 0) {
previous = current;
head.setChild(temp);
scan++;
if (scan == totalSize) {
break;
}
}
temp.setNext(current);
temp.setPrev(temp);
if (scan == 0) {
temp.setNext(head);
head = temp;
}
else {
if (previous != null) {
previous.setNext(temp);
}
if (current != null) {
current.setPrev(temp);
}
}
if (scan == size) {
tail = temp;
previous.setNext(temp);
}
totalSize++;
size++;
}
@Override
public T dequeue() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException("Empty queue");
}
T temp = head.getElement();
head = head.getNext();
size--;
if (isEmpty()) {
tail = null;
}
return temp;
}
Explanation / Answer
@Override
public void enqueue(T element) throws NonComparableElementException {
TernaryNode<T> temp = new TernaryNode<>(element);
if (head == null) {
head = temp;
tail = temp;
size = 1;
totalSize = 1;
return;
}
int scan = 0;
TernaryNode<T> current = head;
TernaryNode<T> previous = null;
Friend cur = (Friend) current.getElement();
while (scan < totalSize && cur.compareTo(element) != 0) {
previous = current;
current = current.getNext();
cur = (Friend) current.getElement();
scan++;
}
if (scan != totalSize) {
current.setChild(temp);
current.increaseChildCount(); //You might need to add this
return;
}
temp.setNext(current);
temp.setPrev(temp);
if (scan == 0) {
temp.setNext(head);
head = temp;
}
else {
if (previous != null) {
previous.setNext(temp);
}
if (current != null) {
current.setPrev(temp);
}
}
if (scan == size) {
tail = temp;
previous.setNext(temp);
}
totalSize++;
size++;
}
@Override
public T dequeue() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException("Empty queue");
}
T temp = head.getElement();
head = head.getNext();
size--;
if (isEmpty()) {
tail = null;
}
return temp;
}
I tried my best to solve. If you have any queries please let me know in the comment section.