add-two-numbers

  • Q : 题解中为什么会出现预先指针 pre
  • A : 因为cur会移动,所以留了个pre,这是个常用的技巧,这样才能找到头的位置,所以pre就没动过,就是为了最后返回结果使用,想想看要是没有pre的话,这个链表就无法使用了,因为头找不到了


  • Q :carry = sum > 9 ? 1 : 0;
  • A : 加法进位只可能是1或0,这样比carry = sum / 10

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode(int x) { val = x; }
    7. * }
    8. */
    9. class Solution {
    10. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    11. ListNode pre = new ListNode(0);
    12. ListNode cur = pre;
    13. int carry = 0;
    14. while (l1 != null || l2 != null) {
    15. int v1 = l1 == null ? 0 : l1.val;
    16. int v2 = l2 == null ? 0 : l2.val;
    17. int sum = v1 + v2 + carry;
    18. carry = sum > 9 ? 1 : 0;
    19. cur.next = new ListNode(sum % 10);
    20. // cur、l1、l2 指针向后移
    21. cur = cur.next;
    22. if (l1 != null) {
    23. l1 = l1.next;
    24. }
    25. if (l2 != null) {
    26. l2 = l2.next;
    27. }
    28. }
    29. if (carry == 1) {
    30. cur.next = new ListNode(1);
    31. }
    32. return pre.next;
    33. }
    34. }