Leetcodes Solution 2 Add Two Numbers

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

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 -> 8Explanation: 342 + 465 = 807.

思路1

List剛好是反向存儲的,直接從頭加到尾,用extra表示滿十進一

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution{public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){ ListNode preHead(0), *p = &preHead; int extra = 0; while(l1 || l2 || extra){ int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra; extra = sum / 10; p->next = new ListNode(sum % 10); p = p->next; l1 = l1 ? l1->next : l1; l2 = l2 ? l2->next : l2; } return preHead.next; }};

推薦閱讀:

浙江大學-數據結構-簡單排序-9.1.2
浙江大學-數據結構-圖:小白專場:C實現哈利波特的考試-7.2.3
浙江大學-數據結構-小白專場:最小路徑問題-7.1.1
浙江大學-數據結構-小白專場:最小路徑問題-7.1.4
浙江大學-數據結構-小白專場:C語言實現如何建立圖-6.5.3

TAG:演算法 | 數據結構 | 編程 |