首页 > 代码库 > 445. Add Two Numbers II
445. Add Two Numbers II
You are given two linked lists representing two non-negative numbers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode reverseL1 = reverseList(l1); ListNode reverseL2 = reverseList(l2); int digit = 0; int curry = 0; ListNode dummy = new ListNode(0); ListNode pre = dummy; while(reverseL2 != null || reverseL1 != null || curry != 0){ int index1 = (reverseL1 == null? 0 : reverseL1.val); int index2 = (reverseL2 == null? 0 : reverseL2.val); digit = (index1 + index2 + curry) % 10; curry = (index1 + index2 + curry) / 10; dummy.next = new ListNode(digit); dummy = dummy.next; if(reverseL1 != null) reverseL1 = reverseL1.next; if(reverseL2 != null) reverseL2 = reverseL2.next; } return reverseList(pre.next); } public ListNode reverseList(ListNode head){ if(head== null || head.next == null) return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode cur = head.next; while(cur != null){ head.next = cur.next; cur.next = dummy.next; dummy.next = cur; cur = head.next; } return dummy.next; } }
445. Add Two Numbers II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。