Add Two Numbers java
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.node
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8git
这题是说: 给出两个链表, 每一个链表表明一个多位整数, 个位在前. 好比2->4->3表明着342. 求这两个链表表明的整数之和(342+465=807), 一样以倒序的链表表示.code
难度: Mediumit
这个题目就是模拟人手算加法的过程, 须要记录进位. 每次把对应位置, 两个节点(若是一个走到头了, 就只算其中一个的值), 加上进位值, 做为结果节点的值, 若是大于9, 须要把进位剥离出来.io
public class Solution { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int addUp = 0; ListNode ret = null; ListNode cur = null; while (l1 != null || l2 != null) { if (cur == null) { cur = ret = new ListNode(0); } else { cur.next = new ListNode(addUp); cur = cur.next; } cur.val += (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val); addUp = cur.val / 10; cur.val = cur.val % 10; if (l1 != null) { l1 = l1.next; } if (l2 != null) { l2 = l2.next; } } if (addUp > 0) { cur.next = new ListNode(addUp); } return ret; } public static void main(String[] args) { Solution s = new Solution(); ListNode a = s.new ListNode(2); a.next = s.new ListNode(4); a.next.next = s.new ListNode(3); ListNode b = s.new ListNode(5); b.next = s.new ListNode(6); // b.next.next = s.new ListNode(4); ListNode c = s.addTwoNumbers(a, b); while (true) { System.out.println(c.val); if (c.next != null) { c = c.next; } else { break; } } } }