/*
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 pre = new ListNode(0);
ListNode cur = pre;
int carry = 0;
while(l1 != null || l2 != null) {
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry;
carry = sum / 10;
sum = sum % 10;
cur.next = new ListNode(sum);
cur = cur.next;<br /> if(l1 != null)<br /> l1 = l1.next;<br /> if(l2 != null)<br /> l2 = l2.next;<br /> }<br /> if(carry == 1) {<br /> cur.next = new ListNode(carry);<br /> }<br /> return pre.next;<br /> }<br />}
作者:guanpengchn
链接:https://leetcode-cn.com/problems/add-two-numbers/solution/hua-jie-suan-fa-2-liang-shu-xiang-jia-by-guanpengc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
/**
- 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 pre = new ListNode();ListNode cru = pre;//进位int corry = 0;while(l1 != null || l2 !=null ){int x = l1 == null? 0:l1.val;int y = l2 == null? 0:l2.val;//注意要加进位int sum = x + y + corry;corry = sum/10;sum = sum%10;cru.next = new ListNode(sum);cru = cru.next;//为空就不能继续下跳if(l1!=null){l1 = l1.next;}if(l2!=null){l2 = l2.next;}}//如果最后一步还有进位,当然进位最大为1if(corry == 1){cru.next = new ListNode(corry);}//注意pre是头节点,而返回要从下一个开始return pre.next;} }
/*** 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 root = new ListNode(0);ListNode cursor = root;int carry = 0;while(l1 != null || l2 != null || carry != 0) {int l1Val = l1 != null ? l1.val : 0;int l2Val = l2 != null ? l2.val : 0;int sumVal = l1Val + l2Val + carry;carry = sumVal / 10;ListNode sumNode = new ListNode(sumVal % 10);cursor.next = sumNode;cursor = sumNode;if(l1 != null) l1 = l1.next;if(l2 != null) l2 = l2.next;}return root.next;}}

