大整数相加链表实现(Add Two Numbers)

        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if(null == l1){
                return l2;
            }
            
            if(null == l2){
                return l1;
            }
            
            // part 1两个list都有值的部分
            ListNode from = l1;
            ListNode to = l2;
            ListNode result = l2;
            boolean leek = false;                          // last calc result >= 10 
            while(null != l1 && null != l2){
                l2.val = l1.val + l2.val + (leek?1:0);
                leek = l2.val >= 10;
                l2.val = l2.val % 10;
                if (l2.next == null || l1.next == null){
                    break;
                }else {
                    l2 = l2.next;
                    l1 = l1.next;
                }
            }
            
            // part 2 
            if (null == l2.next && null == l1.next){
                // 两个list等长
                if (leek){
                    l2.next = new ListNode(1);
                    return result;
                }
            }else if (null == l2.next && null != l1.next) {
                // l1较长
                l2.next = l1.next; // l2指到l1
                l2 = l1.next;  // 跳到下一位
            }else if (null != l2.next && null == l1.next) {
                // l2较长
                l2 = l2.next;  // 跳到下一位
            }
            
            // part 3 较长list进位处理
            while(l2 != null){
                l2.val = l2.val +  (leek?1:0);
                leek = l2.val >= 10;
                l2.val = l2.val % 10;
                if(l2.next == null){
                    break;
                }else {
                    l2 = l2.next;
                }
            }
            
            // part 4 最后的进位
            if (leek){
                l2.next = new ListNode(1);
            }
            
            return result;
        }
    

 

posted @ 2016-02-08 16:37  持幕  阅读(1142)  评论(0编辑  收藏  举报