Java 计算LinkedList中给定数字的出现次数
给定一个类Java 计算LinkedList中给定数字的出现次数,java,linked-list,Java,Linked List,给定一个类LinkedList public class LinkedList { public Node head = null; public class Node { public int value; public Node next; } } 我想添加一个方法public int count(int value),它计算一个数字在列表中出现的次数。 我尝试了以下方法,但并不总是有效,我不确定我做错了什么 public int
LinkedList
public class LinkedList {
public Node head = null;
public class Node {
public int value;
public Node next;
}
}
我想添加一个方法public int count(int value)
,它计算一个数字在列表中出现的次数。
我尝试了以下方法,但并不总是有效,我不确定我做错了什么
public int count(int value) {
int counter = 0;
while(head != null) {
Node tmp = head.next;
while(tmp != null) {
if(head.value == value) {
counter++;
}
tmp = tmp.next;
}
head = head.next;
}
return counter;
}
此方法适用于1 4 3 4 4 5
,int value=4
(该方法应返回3
)
但是对于123445
,int value=4
,它返回1
尝试以下操作:
public int count(int value) {
int counter = 0;
Node tmp = head;
while (tmp != null) {
if(tmp.value == value) { // this line contained your biggest mistake
counter++;
}
tmp = tmp.next;
}
return counter;
}
您在方法中根本没有使用value
参数
我建议您通过使用IDE来改进Java学习,IDE可能会提示代码中的问题。在这种情况下,方法实现中没有使用value
参数
我建议:,或者。我相信还有很多,但这些是我所知道的
这是我的意思的一个小例子:
最简单的方法是:遍历列表并增加包含“value”的每个节点的计数。由于代码中存在一些问题,我试图用注释解释每一行的原因
public int count(int value) {
int count = 0;
// 'tmp' is the node we are currently processing.
// Starting at the head...
Node tmp = head;
// while we not reached the end of the list
while(tmp != null) {
// if the node has the same value we are searching for
if(tmp.value == value) {
// increase count since we found the value
count++;
}
// Go to the next node (null if we reached the end of the list).
tmp = tmp.next;
}
return count;
}
以下是解决问题的递归方法:
int count(int value){
/* dummy node of your head */
LinkedList temp = this.head;
return count(temp, value);
}
private int count(LinkedList temp, int value){
int counter = 0;
if(temp == null){
return 0;
}
/* increment counter, when value is matched */
if(temp.value == value){
counter += 1;
}
counter += count(temp.next, value);
/* return the final result at the end */
return counter;
}
老实说,我很惊讶它居然能起作用。显示的代码完全忽略参数
值
——移动头部
引用可能不是一个好主意。我会假设之后列表是空的。是的,我一发布我的问题就意识到了这一点。这就解决了我的问题。Pablo,tmp.value==value'在这行中使用了参数
value',你为什么说参数根本没有使用@PapaifromBEKOAIL I hadhead.value==tmp.value
。当我意识到我应该与参数值进行比较时,我就编辑了它,因此巴勃罗提到了参数哦,好吧!明白了!谢谢