I'm trying to implement a removeMax() method in this PQ class. The PQ is implemented with a singly-linked list. I can't seem to wrap my head around how you could scan the entire list for the largest value. Any guidance would be appreciated. Here's the whole class:
import java.util.NoSuchElementException;
public class UnorderedLinkedListMaxPQ<Item extends Comparable<Item>> {
private int N;
private Node first;
private class Node {
private Item item;
private Node next;
}
public UnorderedLinkedListMaxPQ() {
first = null;
N = 0;
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
public void insert(Item item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
N++;
}
public Item removeMax() {
if (isEmpty()) { throw new NoSuchElementException("PQ underflow"); }
else if (N == 1) {
Item item = first.item;
first = first.next;
N--;
return item;
}
else if (N != 0) {
// ?
}
}
public String toString() {
Node counter = first;
String string = "";
while (counter != null) {
string = string + counter.item + ", ";
counter = counter.next;
}
return string;
}
private boolean less(Item v, Item w) {
return (v.compareTo(w) < 0);
}
public static void main(String[] args) {
UnorderedLinkedListMaxPQ<Integer> pq = new UnorderedLinkedListMaxPQ<Integer>();
pq.insert(32);
pq.insert(7);
pq.insert(18);
pq.insert(2);
StdOut.println("The priority queue contains (" + pq.toString() + "). \n");
while (!pq.isEmpty())
StdOut.println(pq.removeMax());
}
}