给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
来源:力扣(LeetCode) 链接:> https://leetcode-cn.com/problems/add-two-numbers 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public class Q2 {public static void main(String[] args) {ListNode a = new ListNode(5);ListNode b = new ListNode(4);ListNode c = new ListNode(3);ListNode d = new ListNode(4);a.next = b;b.next = c;c.next = d;ListNode a1 = new ListNode(5);ListNode b1 = new ListNode(6);ListNode c1 = new ListNode(4);ListNode d1 = new ListNode(4);a1.next = b1;b1.next = c1;c1.next = d1;print(a);print(a1);ListNode node = new Q2().addTwoNumbers(a, a1);print(node);}public ListNode addTwoNumbers(Q2.ListNode l1, Q2.ListNode l2) {int f = 0;ListNode node = new ListNode(0);ListNode cur = node;while (l1 != null || l2 != null || f != 0) {int v1 = 0, v2 = 0;if (l1 != null) {v1 = l1.val;l1 = l1.next;}if (l2 != null) {v2 = l2.val;l2 = l2.next;}int sum = v1 + v2 + f;f = sum / 10;cur.next = new ListNode(sum % 10);cur = cur.next;}return node.next;}static class ListNode {int val;ListNode next;ListNode(int x) {val = x;}}/*** 辅助方式,输出链表*/private static void print(ListNode node) {System.out.print("[");while (node != null) {System.out.print(node.val + "->");node = node.next;}System.out.println("]");}}
