/**
* 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) {
ListNode nhead=new ListNode(-1);
ListNode curr=nhead;
int jinwei=0;
ListNode first=l1;
ListNode second=l2;
while(first!=null || second!=null){
int a=0,b=0;
if(first!=null){
a=first.val;
first=first.next;
}
if(second!=null){
b=second.val;
second=second.next;
}
int sum=a+b+jinwei;
jinwei=sum/10;
curr.next=new ListNode(sum%10);
curr=curr.next;
}
if(jinwei>0){
curr.next=new ListNode(jinwei);
}
return nhead.next;
}
}
Leetcode2两数相加
最新推荐文章于 2025-01-26 08:47:43 发布