题解 | 牛群的能量值
牛群的能量值
https://www.nowcoder.com/practice/fc49a20f47ac431981ef17aee6bd7d15
- 原地修改比较复杂,新建节点比较好。
- l1, l2, c 任何一个有效都需要计算下去。
import java.util.*; public class Solution { public ListNode addEnergyValues (ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } ListNode guard = new ListNode(0); ListNode t = guard; int c = 0; while (l1 != null || l2 != null || c != 0) { int sum = c; if (l1 != null) { sum += l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } c = sum / 10; t.next = new ListNode(sum % 10); t = t.next; } return guard.next; } }