我在leetcode的第一题

来源:互联网 发布:日本什么值得买 知乎 编辑:程序博客网 时间:2024/05/17 03:12

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

代码块

/** * 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* l3 = new ListNode(0);        ListNode* temp = l3;        int num;        bool flag = 0;        while (l1 != NULL) {            if (l2 == NULL) {                num = 0;                flag = 1;            } else {                num = l2->val;            }            if (temp->val + l1->val + num >= 10) {                temp->val += l1->val + num - 10;                temp->next = new ListNode(1);                temp = temp->next;            } else {                temp->val += l1->val + num;                if (!flag) {                    if ((l2->next != NULL)||(l1->next != NULL)) {                        temp->next = new ListNode(0);                        temp = temp->next;                    }                } else {                    if (l1->next != NULL) {                        temp->next = new ListNode(0);                        temp = temp->next;                    }                }            }            l1 = l1->next;            if (!flag) l2 = l2->next;        }        while (l2 != NULL) {            if (temp->val + l2->val >= 10) {                temp->val = 0;                temp->next = new ListNode(1);                temp = temp->next;                l2 = l2->next;            } else {                temp->val = temp->val + l2->val;                if (l2->next != NULL) {                    temp->next = new ListNode(0);                    temp = temp->next;                }                l2 = l2->next;            }        }        return l3;    }};

感想

这是leetcode里很简单的一道题,然而我还是花了不少时间。这题我的思路是模仿两个整数相加的竖式计算。此题的数字在链表中倒置存储其实刚好为竖式计算提供了便利。由于拘泥于实现对竖式计算的模拟,加上代码能力还有所欠缺,所以写出的代码看起来有点繁琐。不过作为第一次尝试,我还是好好纪念一下吧。我会继续努力的。

原创粉丝点击