題目node
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.git
You may assume the two numbers do not contain any leading zero, except the number 0 itself.web
輸入: (2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出: 7 -> 0 -> 8
緣由: 342 + 465 = 807.
複製代碼
題目大意:給定2個非空鏈表來表示2個非負整數.位數按照逆序方式存儲,它們的每一個節點只存儲單個數字,將兩數相加返回一個新的鏈表.你能夠假設除了數字0以外,這2個數字都不會以零開頭.面試
2.1 思路算法
咱們使用變量來跟蹤進位,並從包含最低有效位的表頭開始模擬逐位相加的過程.bash
2.2 算法ui
就如同小學數學計算2個數相加通常,咱們首先從低位有效位計算,也就是L1
,L2
的表頭第一個位置開始相加.咱們進行的十進制相加,因此當計算的結果大於9時,就會形成"溢出"的現象.例如5+7=12
.此時,咱們就會把當前爲的值設置爲2,可是溢出的位須要進位.那麼則用carry
存儲,carry = 1
.帶入到下一次迭代計算中.進位的carry
一定是0或者1.2個數累加,須要考慮進位問題.則採用一個變量來保存進位值.spa
2.3 僞代碼code
2.4 複雜度分析orm
O(max(m,n))
,假設m,n分別表示L1,l2長度.上面的算法最多重複max(m,n)
次O(max(m,n))
, 新列表的長度最多max(m,n)+1
2.5 參考代碼
#include <stdio>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* addTwoNumbers(struct ListNode * l1, struct ListNode * l2) {
struct ListNode *dummyHead = (struct ListNode *)malloc(sizeof(struct ListNode));
struct 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 = (struct ListNode *)malloc(sizeof(struct ListNode));
curr->val = sum;
curr = curr->next;
if (p != NULL) p = p->next;
if (q != NULL) q = q->next;
}
if (carry > 0) {
curr->next = (struct ListNode *)malloc(sizeof(struct ListNode));
}
return curr;
}
複製代碼
感謝你們觀看這一篇文章,給你們獻上了iOS開發的188道面試題哦! 加小編的羣就能夠直接獲取哦!551346706