本文共 725 字,大约阅读时间需要 2 分钟。
给定两个链表表示的非负整数,每个节点存储一位数,各位数以逆序存储。将两个数相加,以链表形式返回结果。
例如:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode h = null;
ListNode p = null;
int carry = 0;
while (l1 != null || l2 != null) {
int v = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carry;
ListNode n = new ListNode(v % 10);
carry = v / 10;
if (h == null) {
h = n;
p = h;
} else {
p.next = n;
p = n;
}
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (carry != 0) {
p.next = new ListNode(1);
}
return h;
}
}
转载地址:https://blog.csdn.net/weixin_39987847/article/details/114624911 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!