1 题目
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Linked List Math
2 思路
因为之前做过类似的,刚开始想的就是变为连起来的数字相加。但是,这是不行的,因为链表长度足够长的话,变回越界。
这道题可以直接取两个链表的值,相加即可。唯一考虑的只是进位而已。说起来简单,但实现起来并不容易。下面是一种思路:
像归并排序最后连起来一样的思路。
3 代码
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode headNode = new ListNode(0); ListNode p = headNode; int carry = 0; while (l1 != null && l2 != null) { int var = l1.val + l2.val + carry; carry = var / 10; var = var % 10; ListNode node = new ListNode(var); p.next = node; p = p.next; l1 = l1.next; l2 = l2.next; } //要考虑到前面可能有进位,要加上carry while (l1 != null) { int var = l1.val + carry; carry = var /10; var = var % 10; ListNode node = new ListNode(var); p.next = node; p = p.next; l1 = l1.next; } while (l2 != null) { int var = l2.val + carry; carry = var /10; var = var % 10; ListNode node = new ListNode(var); p.next = node; p = p.next; l2 = l2.next; } //要考虑到最后有个进位,就新建一个节点 if (carry != 0) { ListNode node = new ListNode(carry); p.next = node; p = p.next; } return headNode.next; } }