题解 | #牛群的能量值#
牛群的能量值
https://www.nowcoder.com/practice/fc49a20f47ac431981ef17aee6bd7d15
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ public ListNode addEnergyValues (ListNode l1, ListNode l2) { // write code here if (l1 == null) return l2; if (l2 == null) return l1; ListNode head = null, cur = null, p = l1, q = l2; int c = 0; while (p != null || q != null || c > 0) { int x = (p == null ? 0 : p.val) + (q == null ? 0 : q.val) + c; c = x / 10; ListNode node = new ListNode(x % 10); if (head == null) { head = node; cur = head; } else { cur.next = node; cur = cur.next; } if (p != null) p = p.next; if (q != null) q = q.next; } return head; } }
- 边界值判断,只要其中一个为null,返回另一个
- 定义新链表的头节点,用于结果返回;定义一个 cur,用于新链表的遍历创建;定义两个指针 p、q分别指向 l1和l2,用于遍历
- 定义 c 用于存储进位值
- while循环:
- 条件:只要 p或q有一个不为null,或者 c>1有进位
- 计算 p、q所在位置值的和 x,同时兼容 p、q可能为null 的情况
- 计算进位 c = x / 10
- 构建新阶节点 new ListNode(x % 10)
- 如果 head 为null,说明是第一个节点,直接 head = node,同时 cur 指向 head
- 反之, head 不为null,就将新节点node挂在 cur后面,并将 cur向后走一步
- 然后,p、q都向后走一步
- 循环结束后,返回 head
线性表基础 文章被收录于专栏
链表、递归、栈