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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
知識點:
本題考查的是單鏈表的基本操作。關(guān)于單鏈表,一些基本操作包括單鏈表的創(chuàng)建,添加,插入,刪除。本題只用到了單鏈表的創(chuàng)建和添加。
首先是結(jié)構(gòu)體的建立,這道題已經(jīng)幫我們建立好了結(jié)構(gòu)體,如下:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
一個值,一個指向下一節(jié)點的指針,以及一個構(gòu)造函數(shù)。重點注意:這個構(gòu)造函數(shù)中的參數(shù)并未指定缺省值,所以我們在代碼中不能出現(xiàn)這種語句:
<code> q = new ListNode;</code>
而必須要指定參數(shù)值,例如指定參數(shù)值為0,則代碼應(yīng)寫為
<code> q = new ListNode(0);</code>
關(guān)于單鏈表的創(chuàng)建和添加,必須要有3個指針:頭指針head用于指向單鏈表的開頭,指針p指向單鏈表末尾,指針q用來new一塊空間。添加操作就是用q指針new一塊空間,然后讓p指向q,最后p=p->next即可,代碼如下:
ListNode *head, *p, *q;
head = new ListNode;
p = head;
//assume that the singly-linked list is 0->1->2
for (int i=0; i<3; ++i){
q = new ListNode(i);
p->next = q;
p = p->next;
}
解題思路:
本題實際上就是大數(shù)加法。用一個變量carry表示進位,然后對應(yīng)的位數(shù)相加的時候要加上進位,這個和記為oneSum。那么carry更新為oneSum / 10。除此之外,要考慮兩個單鏈表長度不相等的情況。最后注意一下carry值是否有剩余。若有,則在結(jié)果最后添加上carry;若沒有,則結(jié)束。
C++代碼如下:
/**
* 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* rst = new ListNode(0);
ListNode *p = rst, *q;
int carry = 0, oneSum;
while (l1 != NULL && l2 != NULL){
oneSum = l1->val + l2->val + carry;
q = new ListNode(oneSum % 10);
p->next = q;
p = p->next;
carry = oneSum / 10;
l1 = l1->next;
l2 = l2->next;
}
//to find the remaining number
ListNode* rmn;
if (l1 == NULL && l2 == NULL)
rmn = l1;
else
rmn = l1 != NULL? l1:l2;
//to process the remaining number
while (rmn != NULL){
oneSum = rmn->val + carry;
q = new ListNode(oneSum % 10);
p->next = q;
p = p->next;
carry = oneSum / 10;
rmn = rmn->next;
}
//to check whether carry is still non-zero
if (carry != 0){
q = new ListNode(carry);
p->next = q;
p = p->next;
}
return rst->next;
}
};