明明的leetcode日常: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

这题本身不复杂,就是坑有点多,主要的坑在于:
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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值