Leetcode每天兩題4-第2題和第445題
2. Add Two Numbers
兩個鏈表裡的數據相加生成新的鏈表
思路:把輸入的兩個鏈表從頭往後擼,每兩個相加並添加一個新節點到新鏈表後面,注意要處理下進位問題。最高位的進位問題要最後特殊處理一下
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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* result = new ListNode(-1); ListNode* cur = result; int carry = 0; while (l1 || l2) { int value1 = l1 == NULL ? 0 : l1->val; int value2 = l2 == NULL ? 0 : l2->val; int sum = value1 + value2 + carry; ListNode* tmp = new ListNode(sum % 10); cur->next = tmp; cur = cur->next; carry = sum / 10; if (l1)l1 = l1->next; if (l2)l2 = l2->next; } if (carry != 0) cur->next = new ListNode(carry); return result->next; }};
445. Add Two Numbers II
同上道題差不多,只是這道題的最高位在鏈表的首位置而需要我們從後到前相加。
思路:用棧來保存所有的元素,然後利用棧的後進先出的特點就可以從後往前取數字了,首先遍歷兩個鏈表,將所有數字分別壓入兩個棧s1和s2中,然後循環求和,並創建新的節點,直到棧為空。
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
class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { stack<int> s1, s2; while (l1) { s1.push(l1->val); l1 = l1->next; } while (l2) { s2.push(l2->val); l2 = l2->next; } ListNode* res = new ListNode(0); int sum = 0; while (!s1.empty() || !s2.empty()) { if (!s1.empty()) { sum += s1.top(); s1.pop(); } if (!s2.empty()) { sum += s2.top(); s2.pop(); } res->val = sum % 10; ListNode* head = new ListNode(sum / 10); head->next = res; res = head; sum /= 10; } return res->val == 0 ? res->next : res; }};
推薦閱讀:
※Notes on Implementing Data Structures and Algorithms with Python(三)
※數據結構3.1
※學點演算法之棧的學習與應用
※Python基礎_1.數據結構與演算法_簡單數據結構
※Leetcode之旅|刪除鏈表中重複元素