LeetCode445. 兩數相加 II
阿新 • • 發佈:2020-12-13
☆☆思路:棧 + 頭插法。本題要求不能對節點進行翻轉,那麼對於逆序處理,首先應該想到資料結構【棧】。
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { // 不能對節點進行翻轉,故用到資料結構【棧】 Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); while (l1 != null) { stack1.push(l1.val); l1 = l1.next; } while (l2 != null) { stack2.push(l2.val); l2 = l2.next; } // 【頭插法】 得到 翻轉後的結果連結串列 ListNode head = null; int carry = 0; while (!stack1.isEmpty() || !stack2.isEmpty()) {int x = stack1.size() == 0 ? 0 : stack1.pop(); int y = stack2.size() == 0 ? 0 : stack2.pop(); int temp = x + y + carry; carry = temp / 10; ListNode node = new ListNode(temp % 10); node.next = head; head = node; } if (carry == 1) { ListNode node= new ListNode(carry); node.next = head; head = node; } return head; } }