1. 程式人生 > >Lincode56 - Add Two Numbers - easy

Lincode56 - Add Two Numbers - easy

color list con lin bsp 情況 node 每次 code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;      
 *     }
 * }
 */
public class Solution {
    /**
     * @param l1: the first list
     * @param l2: the second list
     * 
@return: the sum list of l1 and l2 */ public ListNode addLists(ListNode l1, ListNode l2) { // write your code here int digit1 = l1.val; int digit2 = l2.val; int digitS = (digit1 + digit2) % 10; int c = (digit1 + digit2) / 10; l1 = l1.next; l2
= l2.next; ListNode sum = new ListNode(digitS); ListNode head = sum; while (!(l1 == null && l2 == null && c == 0)){ digit1 = l1 == null ? 0 : l1.val; digit2 = l2 == null ? 0 : l2.val; digitS = (digit1 + digit2 + c) % 10; c
= (digit1 + digit2 + c) / 10; l1 = l1 == null ? l1 : l1.next; l2 = l2 == null ? l2 : l2.next; sum.next = new ListNode(digitS); sum = sum.next; } return head; } }

1. 小心處理l1和l2其中有一個先null了的情況,可以digit1 = l1 == null ? 0 : l1.val;
2. 還有小心l1後移的情況,如果l1已經是null了,那就不能後移了,所以要l1 = l1 == null ? l1 : l1.next;
3. 小心後面每次加的時候要多加個c;

Lincode56 - Add Two Numbers - easy