【发布时间】:2020-06-06 21:07:06
【问题描述】:
我正在尝试使用辅助函数递归地在链表中查找“最大值”。我刚开始在课堂上学习这些,我很困惑。我们有一个自定义类,它定义了 Node 类型和另一个函数来计算 Node 或链表的大小。我在比较整数时解决了这个问题,但是我迷路了。这是我的代码: '''
static class Node {
public Node (char item, Node next) { this.item = item; this.next = next; }
public char item;
public Node next;
}
Node first; // this is the only instance variable,
// the access point to the list
// size
//
// a function to compute the size of the list, using a loop
// an empty list has size 0
public int size () {
int count = 0;
for (Node tmp = first; tmp != null; tmp = tmp.next)
count++;
return count;
}
/*
* maxCharacter
*
* a function to compute the 'maximum' character in the list using recursion
* You will want to create a helper function to
* do the recursion
*
* precondition: list is not empty
*
* Examples:
* ["ababcdefb"].maxCharacter() == 'f'
* ["eezzg"].maxCharacter() == 'z'
* ["a"].maxCharacter() == 'a'
*/
public char maxCharacter () {
return maxCharacterHelper(first, first.size());
}
public char maxCharacterHelper(Node first, int index) {
char[] alpha = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int max = 0;
while(index > 0 )
max = alpha.indexOf(first.item) > max ? first.item : max;
maxCharacterHelper(first, index-1);
return max;
}
''' 如果您能解释我如何在保持最大字符的同时递归循环遍历列表,我将不胜感激。
【问题讨论】:
-
我不明白你的while循环,你从来没有减少索引的大小你只需要检查node.next是否为null
标签: java recursion linked-list nodes