2 两数相加(c++)

2019-08-01  本文已影响0人  w_dll

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

/**
 * 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;
    }
};
上一篇下一篇

猜你喜欢

热点阅读