美文网首页
2 两数相加(c++)

2 两数相加(c++)

作者: w_dll | 来源:发表于2019-08-01 18:19 被阅读0次

    时间复杂度有问题,回去修改
    链接

    /**
     * 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 *head = (ListNode*)malloc(sizeof(ListNode));
            ListNode *p =head;
            int temp,flag=0;
            while(l1 || l2 || (flag == 1)){
                temp=0;
                //加操作
                if (l1 != nullptr) 
                    temp+=l1->val;
                if (l2 != nullptr )
                    temp+=l2->val;
    
                if (flag == 1){
                    temp+=1;
                    p->val=temp%10;
                }
                else
                    p->val=temp%10;
                //判断下一次的是否要加1
                if (temp >= 10)
                    flag=1;
                else
                    flag=0;
                //指针后移
                ListNode *next = (ListNode*)malloc(sizeof(ListNode));
                p->next = next;
                p = p->next;
                l1 = l1 ? l1->next : nullptr;
                l2 = l2 ? l2->next : nullptr;
            }
            return head;
        }
    };
    

    相关文章

      网友评论

          本文标题:2 两数相加(c++)

          本文链接:https://www.haomeiwen.com/subject/tcicdctx.html