递归列表 - 计算直到并包括最后一次出现的所有元素的总和内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (44)

int sumLastOcc（Node n，int val）

// n是列表的节点。调用方法时从头开始。

// val是将形成总和的值

``````public class RecursiveList {
static boolean found = false;

public static void main(String[] args) {
RecursiveList list = new RecursiveList();

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

static boolean found = false;

2 个回答

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

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