首页 > 代码库 > add-two-numbers-ii
add-two-numbers-ii
注意:有一种好的方法,是将链表倒转,然后依次相加。
但是,按照题目要求,用了不改变原链表的方法。
就是将两个链表增加到相同长度,然后递归相加,子函数返回后处理进位。
https://leetcode.com/problems/add-two-numbers-ii/
package com.company; import java.util.*; class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } class Solution { ListNode addTwo(ListNode l1, ListNode l2) { //System.out.printf("add two %d, %d \n", l1.val, l2.val); ListNode ret = new ListNode(l1.val + l2.val); if (l1.next != null && l2.next != null) { ret.next = addTwo(l1.next, l2.next); ret.val += ret.next.val / 10; ret.next.val = ret.next.val % 10; } else { ret.next = null; } return ret; } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int l1len = 0; ListNode ln = l1; while (ln != null) { l1len++; ln = ln.next; } int l2len = 0; ln = l2; while (ln != null) { l2len++; ln = ln.next; } if (l1len < l2len) { ln = l1; l1 = l2; l2 = ln; l1len = l1len ^ l2len; l2len = l1len ^ l2len; l1len = l1len ^ l2len; } for (int i=0; i<l1len-l2len; i++) { ln = new ListNode(0); ln.next = l2; l2 = ln; } ln = addTwo(l1, l2); if (ln.val >= 10) { ListNode newHead = new ListNode(ln.val / 10); ln.val = ln.val % 10; newHead.next = ln; ln = newHead; } return ln; } } public class Main { public static void main(String[] args) { System.out.println("Hello!"); Solution solution = new Solution(); ListNode l1 = new ListNode(7); ListNode l11 = new ListNode(2); ListNode l12 = new ListNode(4); ListNode l13 = new ListNode(3); l1.next = l11; l11.next = l12; l12.next = l13; ListNode l2 = new ListNode(5); ListNode l21 = new ListNode(6); ListNode l22 = new ListNode(4); l2.next = l21; l21.next = l22; ListNode ret = solution.addTwoNumbers(l1, l2); System.out.printf("Get ret: \n"); while (ret != null) { System.out.printf("%d", ret.val); ret = ret.next; } System.out.println(); /*Iterator<List<Integer>> iterator = ret.iterator(); while (iterator.hasNext()) { Iterator iter = iterator.next().iterator(); while (iter.hasNext()) { System.out.printf("%d,", iter.next()); } System.out.println(); }*/ System.out.println(); } }
add-two-numbers-ii
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。