I have been working on an assignment for awhile now one of the methods I have to define is a recursive solution to finding the max element in the list. I feel like my solution is close, but I keep getting the last element inserted back, instead of the max element. Can someone point out what I need to do to solve this? * I have been instructed not to use pre-built classes or methods. *
int maxElement () {
if (head == null) {
return -1;
}
else {
Node current = head;
return maxElement (current);
}
}
private int maxElement (Node current) {
Node max;
// If our next node does not exist, our current node has to be max
if (current.getNext() == null) {
return current.getKey();
}
//
else {
if (current.getNext().getKey() > current.getKey()) {
// Assign the larger key as our new max
max = current.getNext();
return maxElement (max);
}
else {
}
}
return maxElement (max.getNext());
}
You have to keep track of the current max in your recursion:
public Node max() {
return maxAux(root, null);
}
private Node maxAux(Node current, Node currentMax) {
if(current == null) {
return currentMax;
}
if(currentMax == null || current.getKey() > currentMax.getKey()) {
return maxAux(current.getNext(), current); // current is the new max
} else {
return maxAux(current.getNext(), currentMax);
}
}
Here is a fairly elegant solution:
public Node max(Node node1, Node node2) {
if (node1 == null || node2 == null)
return node1;
else
return max(node1.getKey() > node2.getKey() ? node1 : node2, node2.getNext());
}
It is called using max(head, head.getNext())
.
If you specifically need to avoid passing the current maximum into the method then:
private static Node currentMax;
private Node maxElement(Node node) {
if (currentMax == null || node == null)
return currentMax;
else if (node.getKey() > currentMax.getKey())
currentMax = node;
return maxElement(node.getNext());
}
This is called with currentMax = head;
then maxElement(head)
.
private Node head, max;
int maxElement () {
if (head == null) {
return -1;
}
else {
Node current = head;
return maxElement (current);
}
}
private int maxElement (Node current) {
// If our next node does not exist, our current node has to be max
if (current.getNext() == null) {
current = this.max;
return this.max.getKey();
}
//
else {
if (current.getNext().getKey() > current.getKey()) {
// Assign the larger key as our new max
this.max = current.getNext();
return maxElement (current.getNext());
}
else {
}
}
return maxElement (max.getNext());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.