add-two-numbers

来源:互联网 发布:江苏普通发票软件下载 编辑:程序博客网 时间:2024/05/22 06:48

You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

下面代码在牛客网发生段错误,但是我能想象的各种情况在vs里测试都没有问题,所以我是漏掉了什么情况没有考虑吗?

代码:

struct ListNode {     int val;     ListNode *next;     ListNode(int x) : val(x), next(NULL) {} };class Solution {public:    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {        if (l1 == NULL)            return l2;        if (l2 == NULL)            return l1;        ListNode *dummy = new ListNode(-1);        ListNode *temp = dummy;        int carry = 0;        while (l1 != NULL && l2 != NULL) {            temp->next = l1;            temp->next->val = l1->val + l2->val + carry;            carry = temp->next->val / 10;            temp->next->val %= 10;            l1 = l1->next;            l2 = l2->next;            temp = temp->next;        }        //l1和l2位数相等但是有进位的情况        if (l1 == NULL && l2 == NULL && carry != 0) {            ListNode *car = new ListNode(carry);            temp->next = car;        }        //位数不等时同样需要把进位加上        if (l1 != NULL) {            temp->next = l1;            temp->next->val = l1->val + carry;        }        if (l2 != NULL) {            temp->next = l2;            temp->next->val = l2->val + carry;        }        return dummy->next;    }};