/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//创建新的头结点
ListNode newRoot=new ListNode(0);
//创建移动指针指向当前创建的头结点
ListNode curPointer=newRoot;
//进位标志
int carry=0;
while(l1 !=null || l2!=null ||carry!=0){
int l1Value= l1!=null ?l1.val:0;
int l2Value= l2!=null ?l2.val:0;
int sumValue=l1Value+l2Value+carry;
//进位是多少?
carry = sumValue/10;
ListNode sumNode=new ListNode(sumValue%10);
curPointer.next=sumNode;
curPointer=sumNode;
if(l1!=null)
l1=l1.next;
if(l2!=null)
l2=l2.next;
}
return newRoot.next;
}
}
2. 两数相加
最新推荐文章于 2025-07-23 13:59:28 发布