LeetCode --- 445. 两数相加 II

解法1 - 递归版本
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    int flow=0;
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        ListNode res1=l1,res2=l2;
        int len1=0,len2=0;
        while(l1!=null){
            len1++;
            l1=l1.next;
        }
        while(l2!=null){
            len2++;
            l2=l2.next;
        }
        ListNode res=len1>len2?add(res1,res2,len1,len2):add(res2,res1,len2,len1);
        if(flow==1) {
            res1=new ListNode(1);
            res1.next=res;
            return res1;
        }
        return res;
    }
    public ListNode add(ListNode l1, ListNode l2,int len1,int len2) {
        int temp;
        if((len1==1)&&(len2==1)){
            temp=l1.val;
            l1.val=(l1.val+l2.val)%10;
            flow=(temp+l2.val)/10;
            return l1;
        } 
        if(len1>len2) {
            temp=l1.val;
            l1.next=add(l1.next, l2,len1-1,len2);
            l1.val=(temp+flow)%10;
            flow=(temp+flow)/10;
            return l1;
        }
        l1.next=add(l1.next, l2.next,len1-1,len2-1);
        temp=l1.val;
        l1.val=(temp+flow+l2.val)%10;
        flow=(temp+flow+l2.val)/10;
        return l1;
    }
}
解法2 - 非递归版本
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
        Stack<Integer> stack1=new Stack();
        Stack<Integer> stack2=new Stack();
        ListNode node1=l1;
        while(node1!=null){
            stack1.push(node1.val);
            node1=node1.next;
        }
        ListNode node2=l2;
        while(node2!=null){
            stack2.push(node2.val);
            node2=node2.next;
        }
        ListNode head=null;
        int flag=0;
        while(!stack1.isEmpty()||!stack2.isEmpty()||flag!=0){
            int value=0;
            if(!stack1.isEmpty())
                value+=stack1.pop();
            if(!stack2.isEmpty())
                value+=stack2.pop();
            value+=flag;
            ListNode node=new ListNode(value%10);
            flag=value/10;
            node.next=head;
            head=node;
        }
       return head;
    }
}
发布了188 篇原创文章 · 获赞 19 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/songzhuo1991/article/details/104173612