1. 程式人生 > 其它 >筆記:Relation Extraction with Explanation

筆記:Relation Extraction with Explanation

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        ListNode l3 = new ListNode();
        ListNode p1 = l1, p2 = l2, p3 = l3;
        int carry = 0;
        while(true) {
            if (p1 == null && p2 == null) break;

            int a = p1 == null ? 0 : p1.val;
            int b = p2 == null ? 0 : p2.val;
            int sum = a + b + carry;
            if (sum >= 10) {
                carry = 1;
                sum -= 10;
            } else {
                carry = 0;
            }

            p3.next = new ListNode(sum);

            if (p1 != null) {
                p1 = p1.next;
            } 

            if (p2 != null) {
                p2 = p2.next;
            } 
            
            p3 = p3.next;
        }

        if(carry == 1) {
            p3.next = new ListNode(1);
        } 

        return l3.next;
    }
}