Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

HELP IN JAVA: I created a circular queue class and starting at the head of the q

ID: 3591313 • Letter: H

Question

HELP IN JAVA:

I created a circular queue class and starting at the head of the queue i have to delete every nth node until only one node remains. Output the String in that last node. This is what I have so far:

public class Queue {

private Node head, tail = null;
int size = 0;

public Queue() {
head = tail = null;
size = 0;

}

//enqueue
public void enqueue(T item) {
Node temp = new Node(item);
if (head == null) {
head = temp;
tail = temp;
} else {
temp.next = head;
tail.next = temp;
tail = temp;

}
size++;

}

//dequeue
public T dequeue(T item) {
Node temp = head;
head = head.next;
tail.next = head;
size--;
return (T) temp.item;
}

//size
public int size() {
if (size == 0) {
}
return size;
}

//peek
public T peek() {
return (T) head.item;
//return item
}

//isEmpty
public boolean isEmpty() {

return (size == 0);
}


//print in queue class
public void print(int i) {
Node curr = head;
while (curr != null) {
System.out.println(curr.item);
curr = curr.next;
}

}

public void delete(int num, Queue q) {

}
}

I need help writing the delete method to delete every nth node until only one node remains and output the String in that last node.

Thanks !!

Explanation / Answer

/** * Deletes node at position n of Queue q. */ public void delete(int num, Queue q) { if (num > N || isEmpty()) throw new NoSuchElementException("Cannot delete element at position: " + num); // if the position to be deleted is greater than the number of nodes or // if the queue itself is empty Node previous = first; int deleteIndex = 1; if(num == deleteIndex){ //special case for first element if(first.next == null) last = null; first = first.next; N--; return; } for (Node node = first; node != null; node = node.next, deleteIndex++) { if (n == deleteIndex) { previous.next = node.next; if (previous.next == null) last = previous; //if deleted element was the last one N--; return; } previous = node; } }