1.英文題目java
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.node
You may assume the two numbers do not contain any leading zero, except the number 0 itself.git
Example:code
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
2.解題get
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { List<ListNode> listNodeList = new ArrayList<>(); int nextValue = 0; //兩個連接相加遍歷過程,只有兩個鏈表都已經遍歷完了並且最後一位相加不大於10 for (; l1 != null || l2 != null || nextValue != 0; ) { int value1 = l1 == null ? 0 : l1.val; int value2 = l2 == null ? 0 : l2.val; listNodeList.add(new ListNode((value1 + value2 + nextValue) % 10)); nextValue = (value1 + value2 + nextValue) / 10; l1 = (l1 == null) ? null : l1.next; l2 = (l2 == null) ? null : l2.next; } //給鏈表增長連接 for (int i = 0; i < listNodeList.size() - 1; i++) { listNodeList.get(i).next = listNodeList.get(i + 1); } return listNodeList.get(0); }