題目來源
將兩個(gè)鏈表的數(shù)相加意乓,我一開始想的直接轉(zhuǎn)為整型,然后相加约素,然后處理届良,然后像上次那樣溢出了,這個(gè)鏈表可是可以無限長的圣猎。所以還是得一個(gè)一個(gè)的進(jìn)行處理士葫,用字符串。
代碼如下:
/**
* 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) {
string num1 = to_string(l1->val), num2 = to_string(l2->val);
while (l1->next != NULL) {
l1 = l1->next;
num1 += to_string(l1->val);
}
while (l2->next != NULL) {
l2 = l2->next;
num2 += to_string(l2->val);
}
ListNode *next = NULL, *cur = NULL;
int i = 1, n1 = num1.size(), n2 = num2.size(), carry = 0;
while (n1 >= i || n2 >= i || carry) {
int a = n1 >= i ? num1[n1-i] - '0' : 0;
int b = n2 >= i ? num2[n2-i] - '0' : 0;
int sum = a + b + carry;
carry = 0;
if (sum > 9)
carry = 1;
next = new ListNode(sum % 10);
next->next = cur;
cur = next;
i++;
}
return cur;
}
};
然后發(fā)現(xiàn)自己有點(diǎn)傻啊送悔,干嘛非得用字符串呢?
用棧就可以了呀慢显,代碼如下:
/**
* 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) {
stack<int> s1;
stack<int> s2;
while (l1 != NULL) {
s1.push(l1->val);
l1 = l1->next;
}
while (l2 != NULL) {
s2.push(l2->val);
l2 = l2->next;
}
ListNode *next = NULL, *cur = NULL;
int carry = 0;
while (!s1.empty() || !s2.empty() || carry) {
int sum = 0;
if (!s1.empty()) {
sum += s1.top();
s1.pop();
}
if (!s2.empty()) {
sum += s2.top();
s2.pop();
}
sum += carry;
carry = 0;
if (sum > 9)
carry = 1;
next = new ListNode(sum % 10);
next->next = cur;
cur = next;
}
return cur;
}
};