LintCode第167题:链表求和

题目

题目解析

题目的意思是对两个整数进行求和运算,只是整数的表示形式有些特殊。每个整数由一个链表表示,链表的每一个结点由整数的某一位构成,其中最低位位于链表开头,最高位位于链表结尾,如:

3->1->5->null//表示513,
5->9->2->null//表示295,
它们的和表示为:
8->0->8->null//808

该题可能会容易忽略在求最高位时的进位,如果有进位时一定要注意构造新的结点。具体见代码。

源码

/**
 * 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
        if(l1==null || l2==null){
            return null;
        }
        int num = (l1.val + l2.val) % 10;
        int flag = (l1.val + l2.val) / 10;
        ListNode head = new ListNode(num);
        ListNode pre = head;
        l1 = l1.next;
        l2 = l2.next;
        
        while(l1!=null || l2!=null)
        {
            int temp1 = 0;
            int temp2 = 0;
            if(l1!=null)
            {
                temp1=l1.val;
                l1=l1.next;
            }
            if(l2!=null)
            {
                temp2=l2.val;
                l2=l2.next;
            }
            ListNode cur = new ListNode((temp1+temp2+flag) % 10);
            flag = (temp1+temp2+flag) / 10;
            pre.next = cur;
            pre = cur;
            
        }
        if(flag!=0)
        {
            ListNode cur = new ListNode(1);
            pre.next = cur;
        }
        return head;
    }
}
posted @ 2017-10-13 09:38  baixiaoshuai  阅读(146)  评论(0编辑  收藏  举报