leetcode_445. Add Two Numbers II 单链表表示的两个大数相加

题目:

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

题意:

两个单链表表示的大数,单链表的第一位为大数的最高有效位,求两个大数相加的和,结果也用单链表表示。假设两个大数没有先导0。


代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        int [] arr1 = new int[100000];    //将第一个单链表存放在数组1中
        int [] arr2 = new int[100000];     //将第二个单链表存放在数组2中
        int len1 = 0;
        int len2 = 0;
        int i=0,j=0,k=0;
        ListNode p = l1;              //定义单链表结点
        
        while( p != null ){          //存储第一个单链表
            arr1[i] = p.val ;
            i++;
            p = p.next;
        }
        len1 = i;
        
        p = l2;
        while( p != null){         //存储第二个单链表
            arr2[j] = p.val ;
            j++;
            p = p.next;
        }
        len2 = j;
        
        i = len1-1; j=len2-1;
        int res[] = new int[Math.max(len1,len2)+1];         //记录两个单链表的和
        while(i >= 0 && j >= 0){
            res[k] += arr1[i]+arr2[j];
            if(res[k]>=10){
                res[k+1] = res[k]/10;
                res[k] = res[k]%10;
            }
            k++;
            i--;
            j--;
        }
        
        while(i>=0){                  //计算剩余的单链表
            res[k] += arr1[i];
            if(res[k]>=10){
                res[k+1] = res[k]/10;
                res[k] = res[k]%10;
            }
            k++;
            i--;
        }
        
        while(j>=0){               //计算剩余的单链表
            res[k] += arr2[j];
            if(res[k]>=10){
                res[k+1] = res[k]/10;
                res[k] = res[k]%10;
            }
            k++;
            j--;
        }
        
        if(res[k] == 0){        //判断最高位是否有进位
            k--;
        }
        
        ListNode head = new ListNode(0);       //定义返回结果的头指针,逆序遍历数组res
        if( k>=0  ){
            p = new ListNode(res[k]);
            head = p;
            k--;
        }
        
        while(k>=0){                    //逆序遍历数组res,将数组用单链表表示
            ListNode q = new ListNode(res[k]);
            p.next = q;
            p = q;
            k--;
        }

        return head;
    }
}


笔记:

表示时间很长。

你可能感兴趣的:(leetcode_445. Add Two Numbers II 单链表表示的两个大数相加)