关闭

LeetCode || Add Two Numbers

161人阅读 评论(0) 收藏 举报
分类:

运行时间为40ms的代码如下(时间有点长):

/**
 * 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 *p1, *p2, *p3;
        p1 = l1;
        p2 = l2;
        int output = 0;
        ListNode *head = new ListNode(0);
        head->next = NULL;
        p3 = head;
        int newDigital;
        int total;
        for(; p1 != NULL && p2 != NULL; ) {
            total = p1->val + p2->val + output;
            if(total >= 10) {
                newDigital = total - 10;
                output = 1;
            }else {
                newDigital = total;
                output = 0;
            }
            p3->next = new ListNode(newDigital);
            p1 = p1->next;
            p2 = p2->next;
            p3 = p3->next;
        }
        if(p1 == NULL) {
            for(; p2 != NULL; ) {
                total = p2->val + output;
                if(total >= 10) {
                    newDigital = total - 10;
                    output = 1;
                }else {
                    newDigital = total;
                    output = 0;
                }
                p3->next = new ListNode(newDigital);
                p2 = p2->next;
                p3 = p3->next;
            }
        }

        if(p2 == NULL) {
            for(; p1 != NULL; ) {
                total = p1->val + output;
                if(total >= 10) {
                    newDigital = total - 10;
                    output = 1;
                }else {
                    newDigital = total;
                    output = 0;
                }
                p3->next = new ListNode(newDigital);
                p1 = p1->next;
                p3 = p3->next;
            }
        }

        if(output == 1) {
            p3->next = new ListNode(1);
            p3 = p3->next;
        }

        p3->next = NULL;

        return head->next;


    }
};
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:45260次
    • 积分:2275
    • 等级:
    • 排名:第16481名
    • 原创:190篇
    • 转载:5篇
    • 译文:0篇
    • 评论:1条
    文章分类
    最新评论