LeeCode

来源:互联网 发布:网络平台建立 编辑:程序博客网 时间:2024/05/28 11:29

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

/** * 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 * result =new ListNode(0) ;        ListNode  *pNode = NULL;        ListNode  *pCurrent = result;        int value = 0;        int data = 0;        int val1 = 0;        int val2 = 0;        while(l1||l2)        {            val1 = l1?l1->val:0;            val2 = l2 ? l2->val:0;            data = val1+val2+data;            pNode = new ListNode(data%10);            data = data/10;            pCurrent->next = pNode;            pCurrent = pNode;            if(l1)                l1 = l1->next;            if(l2)                l2 = l2->next;        }                if(data>0)        {            pNode = new ListNode(data);            pCurrent->next = pNode;        }        return result->next;    }};


0 0