LeetCode----- 2.Add Two Numbers

来源:互联网 发布:磐石投票软件 编辑:程序博客网 时间:2024/06/08 18:55

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

给出了两个非空链表,表示两个非负整数。数字以倒序存储,每个节点都包含一个数字。添加两个数字并将其作为一个链表返回。

提示:本题解法是将两个链表对应的节点进行求和,类似与数学中的2个数相加,注意一点别忽略进位。

public class AddTwoNumbers {public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode result = new ListNode(0);if(l1 ==null && l2 == null) {return result.next;}ListNode currentNode = result;int sum = 0;while(l1 != null || l2 != null || sum != 0) {if(l1 != null) {sum += l1.val;l1 = l1.next;}if(l2 != null) {sum += l2.val;l2 = l2.next;}ListNode node = new ListNode(sum%10);currentNode.next = node;currentNode = node;sum = sum/10;}return result.next;} public static void main(String[] args) {ListNode l10 = new ListNode(2);ListNode l11 = new ListNode(4);ListNode l12 = new ListNode(3);l10.next = l11;l11.next = l12;l12.next = null;ListNode l20 = new ListNode(5);ListNode l21 = new ListNode(6);ListNode l22 = new ListNode(4);l20.next = l21;l21.next = l22;l22.next = null;ListNode node = addTwoNumbers(l10, l20);while(node != null) {if(node.next == null) {System.out.println(node.val);}else {System.out.print(node.val+"->");}node = node.next;}}}class ListNode {int val;ListNode next;ListNode(int x) { val = x;}}


原创粉丝点击