top100-002-两数相加
此道题出现铁憨憨特征。
题目所给链表,逆序,正符合加法计算从低至高,仅需直接相加,高位不够补0即可。
而自己却多此一举采用队列重新存储一遍,对高位不足时不计入加法中。整体数据结构复杂,并且栽与笨重的固化思维,谨记,以作改变。
自己代码:
/** * 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 * 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 * 您可以假设除了数字 0 之外,这两个数都不会以 0 开头 * <p> * 示例: * 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) * 输出:7 -> 0 -> 8 * 原因:342 + 465 = 807 */ import java.util.Scanner; import java.util.concurrent.LinkedBlockingQueue; public class No2 { public static void main(String[] args) throws InterruptedException { Scanner input = new Scanner(System.in); int num1 = input.nextInt(); int num2 = input.nextInt(); int temp1 = num1; int temp2 = num2; ListNode listNode1 = null; ListNode nodetemp1 = null; ListNode nodetemp2 = null; ListNode listNode2 = null; while (temp1 > 0) { ListNode listNodeTemp = new ListNode(temp1 % 10); if (listNode1 == null) { listNode1 = listNodeTemp; nodetemp1 = listNodeTemp; } else { nodetemp1.next = listNodeTemp; nodetemp1 = listNodeTemp; } temp1 = temp1 / 10; } while (temp2 > 0) { ListNode listNodeTemp = new ListNode(temp2 % 10); if (listNode2 == null) { listNode2 = listNodeTemp; nodetemp2 = listNodeTemp; } else { nodetemp2.next = listNodeTemp; nodetemp2 = listNodeTemp; } temp2 = temp2 / 10; } ListNode newList; newList = new No2().addTwoNumbers(listNode1, listNode2); while (newList != null) { System.out.print(newList.val); newList = newList.next; if (newList != null) { System.out.print(" -> "); } } input.close(); } private ListNode addTwoNumbers(ListNode l1, ListNode l2) throws InterruptedException { LinkedBlockingQueue<Integer> queue1 = new LinkedBlockingQueue<>(); LinkedBlockingQueue<Integer> queue2 = new LinkedBlockingQueue<>(); while (l1 != null) { queue1.put(l1.val); l1 = l1.next; } while (l2 != null) { queue2.put(l2.val); l2 = l2.next; } int priority = 0; ListNode newList = null; ListNode nextNode = null; while (!queue1.isEmpty() || !queue2.isEmpty()) { int temp = priority; while (!queue1.isEmpty()) { temp += queue1.poll(); break; } while (!queue2.isEmpty()) { temp += queue2.poll(); break; } if (temp >= 10) { priority = temp / 10; } else { priority = 0; } ListNode node = new ListNode(temp % 10); if (newList != null) { nextNode.next = node; nextNode = node; } else { newList = node; nextNode = node; } } if (priority > 0) { nextNode.next = new ListNode(priority); } return newList; } }
标准答案:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode p = l1, q = l2, curr = dummyHead; int carry = 0; while (p != null || q != null) { int x = (p != null) ? p.val : 0; int y = (q != null) ? q.val : 0; int sum = carry + x + y; carry = sum / 10; curr.next = new ListNode(sum % 10); curr = curr.next; if (p != null) p = p.next; if (q != null) q = q.next; } if (carry > 0) { curr.next = new ListNode(carry); } return dummyHead.next; }