Share my java solution 4ms


  • 0
    X

    public static ListNode addTwoNumbers(ListNode l1,ListNode l2){
    ListNode p1=null;
    ListNode p2=null;

    	p1=l1;
    	p2=l2;
    	while(p1!=null && p2!=null){
    		p1=p1.next;
    		p2=p2.next;
    	}
    	if(p2!=null){
    		//表明l2较长
    		ListNode t=null;
    		t=l1;
    		l1=l2;
    		l2=t;
    	}
    	//现在一定是l1不比l2短了
    	p1=l1;
    	p2=l2;
    	ListNode p1_last=null;
    	int sum=0;
    	int add=0;
    	while(p1!=null && p2!=null){
    		sum=p1.val+p2.val+add;
    		p1.val=sum%10;
    		add=(int)sum/10;
    		if(p1.next==null){
    			p1_last=p1;
    		}
    		p1=p1.next;
    		p2=p2.next;
    	}
    	if(add!=0 && p1==null){
    		p1=new ListNode(add);
    		p1_last.next=p1;
    		p1.next=null;
    	}else if(add!=0 && p1!=null){
    		while(add!=0 && p1!=null){
    			sum=p1.val+add;
    			p1.val=sum%10;
    			add=(int)sum/10;
    			if(add!=0 && p1.next==null){
    				p1_last=p1;
    				p1=new ListNode(add);
    				p1_last.next=p1;
    				p1.next=null;						
    			}
    			p1=p1.next;
    			
    		}
    	}
    	return l1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.