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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章