题干:
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
这题本身不复杂,就是坑有点多,主要的坑在于:
1 两个数的位数不一定相同
2 如果两个数的位数相同,还有要考虑最高位的进位
也就是说,这对结束循环的判断条件提出了要求。
这个代码大概排到55.40%
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* fake_start = new ListNode(0);
ListNode* zero_node = new ListNode(0);
//这是本题唯一接受的链表初始化方式。
//fake_start虚构了一个在链表头之前的指针,用它指向链表头,这样做的目的是便于代码的书写
//zero_node虚构了一个独立的链表节点,它的值为0,它的下一个节点为NULL。它的作用是,当l1和l2长度不一致时,能够用这个节点“填充”不足的节点。
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* past=fake_start;
int onemore=0;
//进位
while(l1 != NULL || l2!=NULL || onemore!=0)
//结束循环的条件:链表到底且没有进位
{
if(l1==NULL)
{
l1=zero_node;
}
if(l2==NULL)
{
l2=zero_node;
}
past->next=new ListNode(l1->val+l2->val+onemore);
ListNode* temp=past->next;
if(temp->val<10) onemore=0;
else
{
onemore=1;
temp->val=temp->val-10;
}
past=temp;
l1=l1->next;
l2=l2->next;
}
ListNode* result=fake_start->next;
delete fake_start;
delete zero_node;//这两个节点是没有用的,需要销毁
return result;
}
};
看了大神的代码,思路和我相同但是更简洁。他没有定义zero_node,而是用三元运算符简单地判断l1或者l2是否为NULL。
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;
}