## 题目地址 https://leetcode.com/problems/add-two-numbers-ii/description/ ## 题目描述 ``` You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Follow up: What if you cannot modify the input lists? In other words, reversing the lists is not allowed. Example: Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7 ``` ## 思路 由于需要从低位开始加,然后进位。 因此可以采用栈来简化操作。 依次将两个链表的值分别入栈stack1和stack2,然后相加入栈stack,进位操作用一个变量carried记录即可。 最后根据stack生成最终的链表即可。 ## 关键点解析 - 栈的基本操作 - carried 变量记录进位 - 循环的终止条件设置成`stack.length > 0` 可以简化操作 - 注意特殊情况, 比如 1 + 99 = 100 ## 代码 ```js /* * @lc app=leetcode id=445 lang=javascript * * [445] Add Two Numbers II * * https://leetcode.com/problems/add-two-numbers-ii/description/ * * algorithms * Medium (49.31%) * Total Accepted: 83.7K * Total Submissions: 169K * Testcase Example: '[7,2,4,3]\n[5,6,4]' * * You are given two non-empty linked lists representing two non-negative * integers. The most significant digit comes first and each of their nodes * contain a single digit. Add the two numbers and return it as a linked list. * * You may assume the two numbers do not contain any leading zero, except the * number 0 itself. * * Follow up: * What if you cannot modify the input lists? In other words, reversing the * lists is not allowed. * * * * Example: * * Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) * Output: 7 -> 8 -> 0 -> 7 * * */ /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var addTwoNumbers = function(l1, l2) { const stack1 = []; const stack2 = []; const stack = []; let cur1 = l1; let cur2 = l2; let curried = 0; while(cur1) { stack1.push(cur1.val); cur1 = cur1.next; } while(cur2) { stack2.push(cur2.val); cur2 = cur2.next; } let a = null; let b = null; while(stack1.length > 0 || stack2.length > 0) { a = Number(stack1.pop()) || 0; b = Number(stack2.pop()) || 0; stack.push((a + b + curried) % 10); if (a + b + curried >= 10) { curried = 1; } else { curried = 0; } } if (curried === 1) { stack.push(1); } const dummy = {}; let current = dummy; while(stack.length > 0) { current.next = { val: stack.pop(), next: null } current = current.next } return dummy.next; }; ```