1. 程式人生 > >[LeetCode]2. Add Two Numbers鏈表相加

[LeetCode]2. Add Two Numbers鏈表相加

pre int 處理 span node new spa ont lag

註意進位的處理和節點為null的處理

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int flag = 0;
        ListNode res = null;
        ListNode temp = null;
        //註意如果進位不是0的話還要添加一個節點
        while (l1!=null||l2!=null||flag!=0)
        {
            int cur = flag;
            flag = 0;
            if
(l1!=null) { cur+=l1.val; l1 = l1.next; } if (l2!=null) { cur+=l2.val; l2 = l2.next; } if (cur>9) { flag = 1; cur%=10; }
if (res==null) { res = new ListNode(cur); temp = res; continue; } temp.next = new ListNode(cur); temp = temp.next; } return res; }

[LeetCode]2. Add Two Numbers鏈表相加