版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cyrususie/article/details/89369848
Add Two Numbers
[Problem Link]
Description
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.
Solution 1
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int flag = 0;
ListNode* ansHead = new ListNode(0);
ListNode* cur = ansHead;
while (1) {
int sum = 0;
if (flag == 1) {
sum += 1;
flag = 0;
}
if (l1 != NULL) {
sum += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
sum += l2->val;
l2 = l2->next;
}
if (sum > 9) {
sum -= 10;
flag = 1;
}
cur->val = sum;
if (l1 == NULL && l2 == NULL && flag == 0) {
break;
}
cur->next = new ListNode(0);
cur = cur->next;
}
return ansHead;
}
};
Solution 2
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; //不要第一个自己随意赋的值,好方法
}
};
Summary
- 看起来像是一道很简单的题,但是我却通过这道题发现了自己对指针掌握的不足。因为要返回一个链表,在链表的循环创建中指针是不断向下指的(ans),所以肯定要保留一个头结点(anshead)。就是在链表和链表头结点上,我纠结了很久。
首先,定义
anshead = new ListNode(0);
ans = anshead;
必须先给anshead分配内存,再把ans指向anshead分配的空间中,每次也必须先给 ans->next = new ListNode(0) 赋值后才能写 ans = ans->next;
总之,必须把ans 指向一个开辟过的空间。
否则, pre->next 在未开辟时指向 0x00000000 若这时 ans = pre->next 那么ans也是0x00000000 若这时给 ans 分配了空间,pre->next 还是0x00000000 因为之前ans没有明确的指定一个地方。 - 做链表题目时要返回链表头,可以将链表头随意赋值,最后return 链表头.next,这样可以不用多一个指针存储链表头。