LintCode | 167. 鏈表求和

你有兩個用鏈表代表的整數,其中每個節點包含一個數字。數字存儲按照在原來整數中相反的順序,使得第一個數字位於鏈表的開頭。寫出一個函數將兩個整數相加,用鏈表形式返回和。


/**
* 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) {
        //先排除兩個鏈表均爲null的情況
        if(l1 == null && l2 == null) return null;

        //carry表示每次相加的進位
        int carry = 0;

        //result用於保存頭節點,temp用於循環,pre用於循環開始後保存temp的上一個節點
        ListNode result = new ListNode(0);
        ListNode temp = result;
        ListNode pre = temp;

        //當兩個鏈表都循環到最後一個節點且沒有進位項時結束循環
        while(l1 != null || l2 != null || carry != 0) {
            //先計算得同一位置的節點與進位的總和
            if(l1 != null) {
                temp.val = temp.val + l1.val;
                l1 = l1.next;
            }
            if(l2 != null) {
                temp.val = temp.val + l2.val;
                l2 = l2.next;
            }
            temp.val = temp.val + carry;

            //將和的進位項另外保存,保留個位
            carry = temp.val / 10;
            temp.val = temp.val - carry * 10;
            temp.next = new ListNode(0);
            pre = temp;
            temp = temp.next;
        }
        pre.next = null;
        return result;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章