gpt4 book ai didi

java - 计算链表中给定数字的出现次数

转载 作者:行者123 更新时间:2023-12-04 07:55:29 35 4
gpt4 key购买 nike

给定一个类 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 )
但对于 1 2 3 4 4 5 , int value = 4 ,它返回 1 .

最佳答案

最简单的方法是:遍历列表并为每个包含“值”的节点增加计数。由于您的代码中有几个问题,我试图用注释解释每一行的原因。

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

关于java - 计算链表中给定数字的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66733643/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com