簡體   English   中英

Java鏈表maxElement遞歸

[英]Java Linked List maxElement recursive

我已經從事一段時間的賦值工作,現在我必須定義的方法之一是在列表中查找max元素的遞歸解決方案。 我覺得我的解決方案已經接近了,但是我一直在找回最后插入的元素,而不是max元素。 有人可以指出我需要做些什么來解決這個問題嗎? *已指示我不要使用預構建的類或方法。 *

        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());
}

您必須在遞歸中跟蹤當前的最大值:

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);
    }
}

這是一個相當優雅的解決方案:

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());
}

使用max(head, head.getNext())調用它。

如果您特別需要避免將當前最大值傳遞給方法,則:

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());
}

這被稱為currentMax = head; 然后是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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM