LeetCode16|两数相加

时间:2022-07-23
本文章向大家介绍LeetCode16|两数相加,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1,问题简述

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

2,示例

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

3,题解思路

使用哨兵节点进行数据的操作

4,题解程序

 
import java.util.ArrayList;
import java.util.List;

public class AddTwoNumbersTest {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        ListNode l12 = new ListNode(4);
        ListNode l13 = new ListNode(3);

        l1.next = l12;
        l12.next = l13;

        ListNode l2 = new ListNode(5);
        ListNode l22 = new ListNode(6);
        ListNode l23 = new ListNode(4);

        l2.next = l22;
        l22.next = l23;
        ListNode listNode = addTwoNumbers(l1, l2);
        System.out.println("listNode = " + listNode);
        List<Integer> list = new ArrayList<>();
        while (listNode != null) {
            list.add(listNode.val);
            listNode = listNode.next;
        }
        System.out.println("list = " + list);
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyNode = new ListNode(0);
        ListNode result = dummyNode;
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        int temp = 0;
        while (l1 != null || l2 != null || temp != 0) {
            if (l1 != null) {
                temp += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                temp += l2.val;
                l2 = l2.next;
            }
            dummyNode.next = new ListNode(temp % 10);
            temp /= 10;
            dummyNode = dummyNode.next;
        }
        return result.next;
    }
}

5,总结,利用哨兵节点去操作的,主要练习一下链表的操作。