[LeetCode] Add Two Numbers

来源:互联网 发布:淘宝网店怎么注销 编辑:程序博客网 时间:2024/06/07 10:29

链表的操作,修改了好多次,进位等小问题比较多。

/** * 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) {        if (l1 == NULL && l2 == NULL) {            return NULL;        }        int add = 0;        ListNode *head = new ListNode(0);        ListNode *current = head;        while (l1 != NULL || l2 != NULL || add != 0) {            int sum = 0;            if (l1 != NULL) {                sum += l1->val;                l1 = l1->next;            }            if (l2 != NULL) {                sum += l2->val;                l2 = l2->next;            }            sum += add;            current->val = sum % 10;            add = sum / 10;            if (l1 != NULL || l2 != NULL || add != 0) {                current->next = new ListNode(0);                current = current->next;            }        }        return head;            }};


0 0
原创粉丝点击