Add Two Numbers

来源:互联网 发布:广告喊话软件 编辑:程序博客网 时间:2024/05/20 04:29


You are giventwo linked lists representing two non-negative numbers. The digits are storedin reverse order and each of their nodes contain a single digit. Add the twonumbers and return it as a linked list.

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 *p = new ListNode(0);        ListNode *head = p;        int c=0;        while (l1 || l2) {            p->next = new ListNode(0);            p = p->next;            if (l1){                p->val += l1->val;                l1 = l1->next;            }            if (l2) {                p->val += l2->val;                l2 =l2->next;            }            p->val += c;            if (p->val>9){                p->val -= 10;                c = 1;            } else {                c = 0;            }        }        if (c) {           p->next = new ListNode(1);         }        p = head->next;        delete head;        head = p;        return head;    }};




0 0
原创粉丝点击