Add Two Numbers

https://leetcode.com/problems/add-two-numbers/

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

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

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11     int j=0,x,y;
12     ListNode an=new ListNode(0);
13     ListNode p=an;
14     while(l1!=null||l2!=null){
15         if(l1!=null){x=l1.val;l1=l1.next;}
16         else x=0;
17         if(l2!=null){y=l2.val;l2=l2.next;}
18         else y=0;
19         
20         int re=x+y+j;
21         if(re>=10){re-=10;j=1;}
22         else j=0;
23         ListNode node=new ListNode(re);
24         p.next=node;p=node;
25     }
26     if(j==1){
27         ListNode node=new ListNode(1);
28         p.next=node;
29     }
30     return an.next;
31         
32     }
33 }
原文地址:https://www.cnblogs.com/qq1029579233/p/4473438.html