这不仅是Java问题。通常这是一个算法问题:
任务是计算直到最后一次出现的值“ val”(包括该方法中的参数)的所有元素的总和。
方法如下:
int sumLastOcc(节点n,int val)
// n是列表的节点。在调用该方法时从头开始。
// val是用来形成总和的值
例如:3 5 2 7 5 1 4
结果:val = 5时为22(调用:sumLastOcc(head,5))
结果:val = 9时为0(调用:sumLastOcc(head,9))
public class RecursiveList {
static Node head;
static boolean found = false;
public static void main(String[] args) {
RecursiveList list = new RecursiveList();
list.addNumber(3);
list.addNumber(5);
list.addNumber(2);
list.addNumber(7);
list.addNumber(5);
list.addNumber(1);
list.addNumber(4);
list.printList();
int result = list.sumLastOcc(head, 5);
System.out.println();
System.out.println(result);
}
private int sumLastOcc(Node n, int val) {
// CODE TO IMPLEMENT
}
return sum;
}
private void addNumber(int number) {
Node curr = head;
Node prev = null;
if (head == null) {
head = new Node(number, null);
} else {
while (curr != null) {
prev = curr;
curr = curr.next;
}
Node newNode = new Node(number, null);
prev.next = newNode;
}
}
// inner node class
private class Node {
Node next;
int value;
Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
private void printList() {
Node curr = head;
Node prev = null;
while (curr != null) {
System.out.print(curr.value + " ");
prev = curr;
curr = curr.next;
}
}
}
可以使用/添加任何全局静态变量,例如:
发现静态布尔值= false;
已定义。 我们不应该使用循环(for,while,...),也不要使用其他方法。只是方法“ private int sumLastOcc(Node n,int val)”应该具有这种魅力。
答案 0 :(得分:0)
我可以解释- 遍历列表直到结尾,并继续添加值。同样在比赛中设置标志(找到为true),以跟踪扣除情况,直到到达终点或找到另一个比赛。找到匹配项后重置计数器。
采用伪代码,如
private int sumLastOcc(Node n, int val) {
if n.next != null
//traverse the list until the end
//add the value to sum
sum = sum + n.value
//keep track of values from the match
if(found)
deduct = deduct + n.value;
//reset the flag when match found
deduct = 0
found = true
//call until reach the end
sumLastOcc(n.next, val)
else
//add the last node value
sum = sum + n.value
//even for the deduct
if (found)
deduct = deduct + n.value;
//lastly return sum - deduct
return found?sum - deduct:0
}
答案 1 :(得分:0)
感谢你们快速而友好的回应。我根据Alexander Pavlov的解释编写了类似的方法。认为这是一种非常好的方法:
private int sumLastOcc(Node n, int val) {
int sumUpTo = 0;
int sumAfter = 0;
if (n.next != null) {
sumAfter = sumAfter + n.value + sumLastOcc(n.next, val);
if (n.value == val) {
found = true;
}
if (found) {
sumUpTo = sumUpTo + sumAfter;
}
} else {
sumAfter = sumAfter + n.value;
if (n.value == val) {
sumUpTo = sumUpTo + sumAfter;
found = true;
}
}
return sumUpTo;
}
所以这解决了:-)