给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
package com.leetcode.part1; /** * @author :shix * @date :Created in 2020/1/26 14:09 * @description:两数相加 * @modified By: */ public class AddTwoNumbers { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head = null;//返回结果 ListNode previousNode = null;//存储上一个节点 boolean flag = false;//是否进位 ListNode p1 = l1; ListNode p2 = l2; while (p1 != null && p2 != null) { int temp = p1.val + p2.val + (flag ? 1 : 0); ListNode node; if (temp >= 10) { node = new ListNode(temp - 10); flag = true; } else { node = new ListNode(temp); flag = false; } if (head == null && previousNode == null) { head = node; previousNode = node; } else { previousNode.next = node; } node.next = null; previousNode = node; p1 = p1.next; p2 = p2.next; } while (p1 != null) { int temp = p1.val + (flag ? 1 : 0); ListNode node; if (temp >= 10) { node = new ListNode(temp - 10); flag = true; } else { node = new ListNode(temp); flag = false; } node.next = null; previousNode.next = node; previousNode = node; p1 = p1.next; } while (p2 != null) { int temp = p2.val + (flag ? 1 : 0); ListNode node; if (temp >= 10) { node = new ListNode(temp - 10); flag = true; } else { node = new ListNode(temp); flag = false; } node.next = null; previousNode.next = node; previousNode = node; p2 = p2.next; } if (flag == true) { ListNode node = new ListNode(1); previousNode.next = node; } return head; } /** * 初始化ListNode * * @param num * @return */ public ListNode initNode(int num) { int temp = num % 10; ListNode head = null; ListNode previousNode = null; while (temp != 0) { ListNode node = new ListNode(temp); node.next = null; if (head == null && previousNode == null) { head = node; previousNode = node; } else { previousNode.next = node; } num = num / 10; temp = num % 10; previousNode = node; } return head; } public static void main(String[] args) { AddTwoNumbers add = new AddTwoNumbers(); //初始化两个链表 ListNode l1 = add.initNode(342); ListNode l2 = add.initNode(465); //两数相加 ListNode result = add.addTwoNumbers(l1, l2); // 打印结果 add.printResult(result); } private void printResult(ListNode result) { //打印结果 System.out.print("结果:"); while (result != null) { System.out.print(result.val); if (result.next != null) { System.out.print("->"); } result = result.next; } System.out.println(""); } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } }
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
码code玩~~~
原文地址:https://www.cnblogs.com/shix0909/p/12234297.html
时间: 2024-10-08 07:14:50